repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/CSharp/BraceMatching/StringLiteralBraceMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using 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.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.BraceMatching { [ExportBraceMatcher(LanguageNames.CSharp)] internal class StringLiteralBraceMatcher : IBraceMatcher { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StringLiteralBraceMatcher() { } public async Task<BraceMatchingResult?> FindBracesAsync(Document document, int position, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position); if (!token.ContainsDiagnostics) { if (token.IsKind(SyntaxKind.StringLiteralToken)) { if (token.IsVerbatimStringLiteral()) { return new BraceMatchingResult( new TextSpan(token.SpanStart, 2), new TextSpan(token.Span.End - 1, 1)); } else { return new BraceMatchingResult( new TextSpan(token.SpanStart, 1), new TextSpan(token.Span.End - 1, 1)); } } else if (token.IsKind(SyntaxKind.InterpolatedStringStartToken, SyntaxKind.InterpolatedVerbatimStringStartToken)) { if (token.Parent is InterpolatedStringExpressionSyntax interpolatedString) { return new BraceMatchingResult(token.Span, interpolatedString.StringEndToken.Span); } } else if (token.IsKind(SyntaxKind.InterpolatedStringEndToken)) { if (token.Parent is InterpolatedStringExpressionSyntax interpolatedString) { return new BraceMatchingResult(interpolatedString.StringStartToken.Span, token.Span); } } } 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.ComponentModel.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.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.BraceMatching { [ExportBraceMatcher(LanguageNames.CSharp)] internal class StringLiteralBraceMatcher : IBraceMatcher { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public StringLiteralBraceMatcher() { } public async Task<BraceMatchingResult?> FindBracesAsync(Document document, int position, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position); if (!token.ContainsDiagnostics) { if (token.IsKind(SyntaxKind.StringLiteralToken)) { if (token.IsVerbatimStringLiteral()) { return new BraceMatchingResult( new TextSpan(token.SpanStart, 2), new TextSpan(token.Span.End - 1, 1)); } else { return new BraceMatchingResult( new TextSpan(token.SpanStart, 1), new TextSpan(token.Span.End - 1, 1)); } } else if (token.IsKind(SyntaxKind.InterpolatedStringStartToken, SyntaxKind.InterpolatedVerbatimStringStartToken)) { if (token.Parent is InterpolatedStringExpressionSyntax interpolatedString) { return new BraceMatchingResult(token.Span, interpolatedString.StringEndToken.Span); } } else if (token.IsKind(SyntaxKind.InterpolatedStringEndToken)) { if (token.Parent is InterpolatedStringExpressionSyntax interpolatedString) { return new BraceMatchingResult(interpolatedString.StringStartToken.Span, token.Span); } } } return null; } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Workspaces/Core/Portable/Diagnostics/AbstractDiagnosticPropertiesService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Diagnostics { internal abstract class AbstractDiagnosticPropertiesService : IDiagnosticPropertiesService { public ImmutableDictionary<string, string> GetAdditionalProperties(Diagnostic diagnostic) => GetAdditionalProperties(diagnostic, GetCompilation()); protected abstract Compilation GetCompilation(); private static ImmutableDictionary<string, string> GetAdditionalProperties( Diagnostic diagnostic, Compilation compilation) { var assemblyIds = compilation.GetUnreferencedAssemblyIdentities(diagnostic); var requiredVersion = Compilation.GetRequiredLanguageVersion(diagnostic); if (assemblyIds.IsDefaultOrEmpty && requiredVersion == null) { return null; } var result = ImmutableDictionary.CreateBuilder<string, string>(); if (!assemblyIds.IsDefaultOrEmpty) { result.Add( DiagnosticPropertyConstants.UnreferencedAssemblyIdentity, assemblyIds[0].GetDisplayName()); } if (requiredVersion != null) { result.Add( DiagnosticPropertyConstants.RequiredLanguageVersion, requiredVersion); } return result.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.Collections.Immutable; namespace Microsoft.CodeAnalysis.Diagnostics { internal abstract class AbstractDiagnosticPropertiesService : IDiagnosticPropertiesService { public ImmutableDictionary<string, string> GetAdditionalProperties(Diagnostic diagnostic) => GetAdditionalProperties(diagnostic, GetCompilation()); protected abstract Compilation GetCompilation(); private static ImmutableDictionary<string, string> GetAdditionalProperties( Diagnostic diagnostic, Compilation compilation) { var assemblyIds = compilation.GetUnreferencedAssemblyIdentities(diagnostic); var requiredVersion = Compilation.GetRequiredLanguageVersion(diagnostic); if (assemblyIds.IsDefaultOrEmpty && requiredVersion == null) { return null; } var result = ImmutableDictionary.CreateBuilder<string, string>(); if (!assemblyIds.IsDefaultOrEmpty) { result.Add( DiagnosticPropertyConstants.UnreferencedAssemblyIdentity, assemblyIds[0].GetDisplayName()); } if (requiredVersion != null) { result.Add( DiagnosticPropertyConstants.RequiredLanguageVersion, requiredVersion); } return result.ToImmutable(); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/CSharpTest2/Recommendations/ForKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ForKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideFor() { await VerifyKeywordAsync(AddInsideMethod( @"for (;;) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideForInsideFor() { await VerifyKeywordAsync(AddInsideMethod( @"for (;;) for (;;) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideForBlock() { await VerifyKeywordAsync(AddInsideMethod( @"for (;;) { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFor1() { await VerifyAbsenceAsync(AddInsideMethod( @"for $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFor2() { await VerifyAbsenceAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFor3() { await VerifyAbsenceAsync(AddInsideMethod( @"for (;$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFor4() { await VerifyAbsenceAsync(AddInsideMethod( @"for (;;$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync(@"class C { $$ }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ForKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideFor() { await VerifyKeywordAsync(AddInsideMethod( @"for (;;) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideForInsideFor() { await VerifyKeywordAsync(AddInsideMethod( @"for (;;) for (;;) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideForBlock() { await VerifyKeywordAsync(AddInsideMethod( @"for (;;) { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFor1() { await VerifyAbsenceAsync(AddInsideMethod( @"for $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFor2() { await VerifyAbsenceAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFor3() { await VerifyAbsenceAsync(AddInsideMethod( @"for (;$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFor4() { await VerifyAbsenceAsync(AddInsideMethod( @"for (;;$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync(@"class C { $$ }"); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/DimKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Dim" keyword in all appropriate contexts. ''' </summary> Friend Class DimKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Dim", VBFeaturesResources.Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) ' It can start a statement If context.IsMultiLineStatementContext Then Return s_keywords End If If context.IsTypeMemberDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts ' In Dev10, we don't show it after Const (but will after ReadOnly, even though the formatter removes it) If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Field) AndAlso modifiers.MutabilityOrWithEventsKeyword.Kind <> SyntaxKind.ConstKeyword AndAlso modifiers.DimKeyword.Kind = SyntaxKind.None Then Return s_keywords End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations ''' <summary> ''' Recommends the "Dim" keyword in all appropriate contexts. ''' </summary> Friend Class DimKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Dim", VBFeaturesResources.Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) ' It can start a statement If context.IsMultiLineStatementContext Then Return s_keywords End If If context.IsTypeMemberDeclarationKeywordContext Then Dim modifiers = context.ModifierCollectionFacts ' In Dev10, we don't show it after Const (but will after ReadOnly, even though the formatter removes it) If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Field) AndAlso modifiers.MutabilityOrWithEventsKeyword.Kind <> SyntaxKind.ConstKeyword AndAlso modifiers.DimKeyword.Kind = SyntaxKind.None Then Return s_keywords End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_StackAllocArrayCreationAndInitializer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_StackAllocArrayCreationAndInitializer : SemanticModelTestBase { [Fact] public void SimpleStackAllocArrayCreation_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[1]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[1]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[1]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[1]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_UserDefinedType() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc M[1]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[1]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[1]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[1]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_ConstantDimension() { string source = @" struct M { } class C { public void F() { const int dimension = 1; var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): ILocalReferenceOperation: dimension (OperationKind.LocalReference, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(9,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(9, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_NonConstantDimension() { string source = @" struct M { } class C { public void F(int dimension) { var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_DimensionWithImplicitConversion() { string source = @" struct M { } class C { public void F(char dimension) { var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Char, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_DimensionWithExplicitConversion() { string source = @" struct M { } class C { public void F(object dimension) { var a = /*<bind>*/stackalloc M[(int)dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... )dimension]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[(int)dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[(int)dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc int[] { 42 }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[] { 42 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_PrimitiveTypeWithExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[1] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[1] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[1] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[1] { 42 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_PrimitiveTypeWithIncorrectExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[2] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[2] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0847: An array initializer of length '2' is expected // var a = /*<bind>*/stackalloc int[2] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[2] { 42 }").WithArguments("2").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_PrimitiveTypeWithNonConstantExplicitDimension() { string source = @" class C { public void F(int dimension) { var a = /*<bind>*/stackalloc int[dimension] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... ion] { 42 }') Children(2): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'dimension') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0150: A constant value is expected // var a = /*<bind>*/stackalloc int[dimension] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstantExpected, "dimension").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_UserDefinedType() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc M[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... { new M() }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc ... { new M() }') IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M, IsInvalid) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[] { new M() }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[] { new M() }").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_ImplicitlyTyped() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[] { new M() }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc[] { new M() }') IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M, IsInvalid) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc[] { new M() }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc[] { new M() }").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializerAndDimension() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/stackalloc[]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[]/*</bind>*/') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'stackalloc[]/*</bind>*/') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,50): error CS1514: { expected // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 50), // file.cs(6,50): error CS1513: } expected // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 50), // file.cs(6,27): error CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializer() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/stackalloc[2]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[2]/*</bind>*/') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'stackalloc[2]/*</bind>*/') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,38): error CS8381: "Invalid rank specifier: expected ']' // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "2").WithLocation(6, 38), // file.cs(6,51): error CS1514: { expected // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 51), // file.cs(6,51): error CS1513: } expected // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 51), // file.cs(6,27): error CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[2]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_MultipleInitializersWithConversions() { string source = @" class C { public void F() { var a = 42; var b = /*<bind>*/stackalloc[] { 2, a, default }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[ ... , default }') Children(4): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid, IsImplicit) (Syntax: 'stackalloc[ ... , default }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'a') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'default') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: 'default') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var b = /*<bind>*/stackalloc[] { 2, a, default }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc[] { 2, a, default }").WithLocation(7, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_MissingDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[]') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,41): error CS1586: Array creation must have array size or array initializer // var a = /*<bind>*/stackalloc int[]/*</bind>*/; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 41) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvalidInitializer() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[] { 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[] { 1 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc int[] { 1 }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[] { 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[] { 1 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_MissingExplicitCast() { string source = @" class C { public void F(object b) { var a = /*<bind>*/stackalloc int[b]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[b]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'b') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/stackalloc int[b]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("object", "int").WithLocation(6, 42), // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[b]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[b]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreation_InvocationExpressionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; } public int M() => 1; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[M()]') Children(1): IInvocationOperation ( System.Int32 C.M()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[M()]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreation_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[(int)M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Object C.M()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[(int)M()]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvocationExpressionAsDimension() { string source = @" class C { public static void F() { var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'M()') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0120: An object reference is required for the non-static field, method, or property 'C.M()' // var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectRequired, "M").WithArguments("C.M()").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; } public C M() => new C(); } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[(int)M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( C C.M()) (OperationKind.Invocation, Type: C, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0030: Cannot convert type 'C' to 'int' // var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)M()").WithArguments("C", "int").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_ConstantConversion() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[0.0]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: '0.0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsInvalid) (Syntax: '0.0') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "0.0").WithArguments("double", "int").WithLocation(6, 42), // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[0.0]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_StackAllocArrayCreationAndInitializer : SemanticModelTestBase { [Fact] public void SimpleStackAllocArrayCreation_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[1]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[1]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[1]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[1]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_UserDefinedType() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc M[1]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[1]') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[1]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[1]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_ConstantDimension() { string source = @" struct M { } class C { public void F() { const int dimension = 1; var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): ILocalReferenceOperation: dimension (OperationKind.LocalReference, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(9,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(9, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_NonConstantDimension() { string source = @" struct M { } class C { public void F(int dimension) { var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_DimensionWithImplicitConversion() { string source = @" struct M { } class C { public void F(char dimension) { var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc M[dimension]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Char, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_DimensionWithExplicitConversion() { string source = @" struct M { } class C { public void F(object dimension) { var a = /*<bind>*/stackalloc M[(int)dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... )dimension]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'dimension') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[(int)dimension]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[(int)dimension]").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc int[] { 42 }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[] { 42 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_PrimitiveTypeWithExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[1] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[1] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[1] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[1] { 42 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_PrimitiveTypeWithIncorrectExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[2] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[2] { 42 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0847: An array initializer of length '2' is expected // var a = /*<bind>*/stackalloc int[2] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[2] { 42 }").WithArguments("2").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_PrimitiveTypeWithNonConstantExplicitDimension() { string source = @" class C { public void F(int dimension) { var a = /*<bind>*/stackalloc int[dimension] { 42 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... ion] { 42 }') Children(2): IParameterReferenceOperation: dimension (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'dimension') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0150: A constant value is expected // var a = /*<bind>*/stackalloc int[dimension] { 42 }/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstantExpected, "dimension").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_UserDefinedType() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc M[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc ... { new M() }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc ... { new M() }') IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M, IsInvalid) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc M[] { new M() }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc M[] { new M() }").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_ImplicitlyTyped() { string source = @" struct M { } class C { public void F() { var a = /*<bind>*/stackalloc[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[] { new M() }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc[] { new M() }') IObjectCreationOperation (Constructor: M..ctor()) (OperationKind.ObjectCreation, Type: M, IsInvalid) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc[] { new M() }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc[] { new M() }").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializerAndDimension() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/stackalloc[]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[]/*</bind>*/') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'stackalloc[]/*</bind>*/') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,50): error CS1514: { expected // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 50), // file.cs(6,50): error CS1513: } expected // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 50), // file.cs(6,27): error CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/stackalloc[]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializer() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/stackalloc[2]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[2]/*</bind>*/') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'stackalloc[2]/*</bind>*/') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,38): error CS8381: "Invalid rank specifier: expected ']' // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "2").WithLocation(6, 38), // file.cs(6,51): error CS1514: { expected // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 51), // file.cs(6,51): error CS1513: } expected // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 51), // file.cs(6,27): error CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/stackalloc[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[2]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationWithInitializer_MultipleInitializersWithConversions() { string source = @" class C { public void F() { var a = 42; var b = /*<bind>*/stackalloc[] { 2, a, default }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc[ ... , default }') Children(4): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid, IsImplicit) (Syntax: 'stackalloc[ ... , default }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'a') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'default') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: 'default') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var b = /*<bind>*/stackalloc[] { 2, a, default }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc[] { 2, a, default }").WithLocation(7, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitStackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_MissingDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[]') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,41): error CS1586: Array creation must have array size or array initializer // var a = /*<bind>*/stackalloc int[]/*</bind>*/; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 41) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvalidInitializer() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[] { 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[] { 1 }') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'stackalloc int[] { 1 }') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[] { 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[] { 1 }").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_MissingExplicitCast() { string source = @" class C { public void F(object b) { var a = /*<bind>*/stackalloc int[b]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[b]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'b') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/stackalloc int[b]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("object", "int").WithLocation(6, 42), // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[b]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[b]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreation_InvocationExpressionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; } public int M() => 1; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[M()]') Children(1): IInvocationOperation ( System.Int32 C.M()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[M()]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreation_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[(int)M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Object C.M()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[(int)M()]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvocationExpressionAsDimension() { string source = @" class C { public static void F() { var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'M()') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0120: An object reference is required for the non-static field, method, or property 'C.M()' // var a = /*<bind>*/stackalloc int[M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectRequired, "M").WithArguments("C.M()").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void StackAllocArrayCreationErrorCase_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; } public C M() => new C(); } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[(int)M()]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( C C.M()) (OperationKind.Invocation, Type: C, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0030: Cannot convert type 'C' to 'int' // var a = /*<bind>*/stackalloc int[(int)M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)M()").WithArguments("C", "int").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void SimpleStackAllocArrayCreation_ConstantConversion() { string source = @" class C { public void F() { var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'stackalloc int[0.0]') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: '0.0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsInvalid) (Syntax: '0.0') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,42): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "0.0").WithArguments("double", "int").WithLocation(6, 42), // file.cs(6,27): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var a = /*<bind>*/stackalloc int[0.0]/*</bind>*/; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[0.0]").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<StackAllocArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Workspaces/Core/Portable/Diagnostics/IDiagnosticPropertiesService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Host; namespace Microsoft.CodeAnalysis.Diagnostics { internal interface IDiagnosticPropertiesService : ILanguageService { ImmutableDictionary<string, string> GetAdditionalProperties(Diagnostic diagnostic); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Host; namespace Microsoft.CodeAnalysis.Diagnostics { internal interface IDiagnosticPropertiesService : ILanguageService { ImmutableDictionary<string, string> GetAdditionalProperties(Diagnostic diagnostic); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Interactive/HostProcess/InteractiveHost64.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets"/> <PropertyGroup> <Prefer32Bit>false</Prefer32Bit> <OutputType>Exe</OutputType> <TargetFrameworks>net472;net5.0-windows7.0</TargetFrameworks> <RuntimeIdentifier>win10-x64</RuntimeIdentifier> <UseWindowsForms>true</UseWindowsForms> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> <!-- Publishing (only precompile binaries when building on CI to avoid slowing down dev builds by ~10s) --> <PublishReadyToRun Condition="'$(ContinuousIntegrationBuild)' == 'true'">true</PublishReadyToRun> <SelfContained>false</SelfContained> <PublishDocumentationFiles>false</PublishDocumentationFiles> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> </ItemGroup> <Target Name="PublishProjectOutputGroup" DependsOnTargets="Publish" Returns="@(_PublishedFiles)"> <ItemGroup> <!-- Need to include and then update items (https://github.com/microsoft/msbuild/issues/1053) --> <_PublishedFiles Include="$(PublishDir)**\*.*" /> <_PublishedFiles Remove="@(_PublishedFiles)" Condition="'%(Extension)' == '.pdb'" /> <!-- Include .rsp file --> <_PublishedFiles Include="$(MSBuildProjectDirectory)\Desktop\CSharpInteractive.rsp" Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'" /> <_PublishedFiles Include="$(MSBuildProjectDirectory)\Core\CSharpInteractive.rsp" Condition="'$(TargetFrameworkIdentifier)' != '.NETFramework'" /> <!-- Set TargetPath --> <_PublishedFiles Update="@(_PublishedFiles)" TargetPath="%(RecursiveDir)%(Filename)%(Extension)" /> <!-- Set NGEN metadata --> <_PublishedFiles Update="@(_PublishedFiles)" Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework' and ('%(Extension)' == '.dll' or '%(Extension)' == '.exe')"> <Ngen>true</Ngen> <NgenPriority>3</NgenPriority> <NgenArchitecture Condition="'%(Filename)' != 'InteractiveHost64'">All</NgenArchitecture> <NgenArchitecture Condition="'%(Filename)' == 'InteractiveHost64'">X64</NgenArchitecture> <NgenApplication>[installDir]\Common7\IDE\$(CommonExtensionInstallationRoot)\$(LanguageServicesExtensionInstallationFolder)\InteractiveHost\Desktop\InteractiveHost64.exe</NgenApplication> </_PublishedFiles> </ItemGroup> </Target> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets"/> <PropertyGroup> <Prefer32Bit>false</Prefer32Bit> <OutputType>Exe</OutputType> <TargetFrameworks>net472;net5.0-windows7.0</TargetFrameworks> <RuntimeIdentifier>win10-x64</RuntimeIdentifier> <UseWindowsForms>true</UseWindowsForms> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> <!-- Publishing (only precompile binaries when building on CI to avoid slowing down dev builds by ~10s) --> <PublishReadyToRun Condition="'$(ContinuousIntegrationBuild)' == 'true'">true</PublishReadyToRun> <SelfContained>false</SelfContained> <PublishDocumentationFiles>false</PublishDocumentationFiles> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> </ItemGroup> <Target Name="PublishProjectOutputGroup" DependsOnTargets="Publish" Returns="@(_PublishedFiles)"> <ItemGroup> <!-- Need to include and then update items (https://github.com/microsoft/msbuild/issues/1053) --> <_PublishedFiles Include="$(PublishDir)**\*.*" /> <_PublishedFiles Remove="@(_PublishedFiles)" Condition="'%(Extension)' == '.pdb'" /> <!-- Include .rsp file --> <_PublishedFiles Include="$(MSBuildProjectDirectory)\Desktop\CSharpInteractive.rsp" Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'" /> <_PublishedFiles Include="$(MSBuildProjectDirectory)\Core\CSharpInteractive.rsp" Condition="'$(TargetFrameworkIdentifier)' != '.NETFramework'" /> <!-- Set TargetPath --> <_PublishedFiles Update="@(_PublishedFiles)" TargetPath="%(RecursiveDir)%(Filename)%(Extension)" /> <!-- Set NGEN metadata --> <_PublishedFiles Update="@(_PublishedFiles)" Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework' and ('%(Extension)' == '.dll' or '%(Extension)' == '.exe')"> <Ngen>true</Ngen> <NgenPriority>3</NgenPriority> <NgenArchitecture Condition="'%(Filename)' != 'InteractiveHost64'">All</NgenArchitecture> <NgenArchitecture Condition="'%(Filename)' == 'InteractiveHost64'">X64</NgenArchitecture> <NgenApplication>[installDir]\Common7\IDE\$(CommonExtensionInstallationRoot)\$(LanguageServicesExtensionInstallationFolder)\InteractiveHost\Desktop\InteractiveHost64.exe</NgenApplication> </_PublishedFiles> </ItemGroup> </Target> </Project>
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Workspaces/Core/Portable/Utilities/NullableStructExtensions.cs
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities { internal static class NullableStructExtensions { public static void Deconstruct<T>(this T? value, out T valueOrDefault, out bool hasValue) where T : struct { valueOrDefault = value.GetValueOrDefault(); hasValue = value.HasValue; } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities { internal static class NullableStructExtensions { public static void Deconstruct<T>(this T? value, out T valueOrDefault, out bool hasValue) where T : struct { valueOrDefault = value.GetValueOrDefault(); hasValue = value.HasValue; } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/Core/Implementation/Classification/CopyPasteAndPrintingClassificationBufferTaggerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { /// <summary> /// This is the tagger we use for buffer classification scenarios. It is only used for /// IAccurateTagger scenarios. Namely: Copy/Paste and Printing. We use an 'Accurate' buffer /// tagger since these features need to get classification tags for the entire file. /// /// i.e. if you're printing, you want semantic classification even for code that's not in view. /// The same applies to copy/pasting. /// </summary> [Export(typeof(ITaggerProvider))] [TagType(typeof(IClassificationTag))] [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] internal partial class CopyPasteAndPrintingClassificationBufferTaggerProvider : ForegroundThreadAffinitizedObject, ITaggerProvider { private readonly IAsynchronousOperationListener _asyncListener; private readonly ClassificationTypeMap _typeMap; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CopyPasteAndPrintingClassificationBufferTaggerProvider( IThreadingContext threadingContext, ClassificationTypeMap typeMap, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext) { _typeMap = typeMap; _asyncListener = listenerProvider.GetListener(FeatureAttribute.Classification); } public IAccurateTagger<T>? CreateTagger<T>(ITextBuffer buffer) where T : ITag { this.AssertIsForeground(); // The LSP client will handle producing tags when running under the LSP editor. // Our tagger implementation should return nothing to prevent conflicts. if (buffer.IsInLspEditorContext()) { return null; } return new Tagger(this, buffer, _asyncListener) as IAccurateTagger<T>; } ITagger<T>? ITaggerProvider.CreateTagger<T>(ITextBuffer buffer) => CreateTagger<T>(buffer); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { /// <summary> /// This is the tagger we use for buffer classification scenarios. It is only used for /// IAccurateTagger scenarios. Namely: Copy/Paste and Printing. We use an 'Accurate' buffer /// tagger since these features need to get classification tags for the entire file. /// /// i.e. if you're printing, you want semantic classification even for code that's not in view. /// The same applies to copy/pasting. /// </summary> [Export(typeof(ITaggerProvider))] [TagType(typeof(IClassificationTag))] [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] internal partial class CopyPasteAndPrintingClassificationBufferTaggerProvider : ForegroundThreadAffinitizedObject, ITaggerProvider { private readonly IAsynchronousOperationListener _asyncListener; private readonly ClassificationTypeMap _typeMap; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CopyPasteAndPrintingClassificationBufferTaggerProvider( IThreadingContext threadingContext, ClassificationTypeMap typeMap, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext) { _typeMap = typeMap; _asyncListener = listenerProvider.GetListener(FeatureAttribute.Classification); } public IAccurateTagger<T>? CreateTagger<T>(ITextBuffer buffer) where T : ITag { this.AssertIsForeground(); // The LSP client will handle producing tags when running under the LSP editor. // Our tagger implementation should return nothing to prevent conflicts. if (buffer.IsInLspEditorContext()) { return null; } return new Tagger(this, buffer, _asyncListener) as IAccurateTagger<T>; } ITagger<T>? ITaggerProvider.CreateTagger<T>(ITextBuffer buffer) => CreateTagger<T>(buffer); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/LanguageServer/Protocol/Handler/Definitions/GoToDefinitionHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.MetadataAsSource; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentDefinitionName)] internal class GoToDefinitionHandler : AbstractGoToDefinitionHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService) : base(metadataAsSourceFileService) { } public override string Method => LSP.Methods.TextDocumentDefinitionName; public override Task<LSP.Location[]> HandleRequestAsync(LSP.TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) => GetDefinitionAsync(request, typeOnly: false, context, 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MetadataAsSource; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentDefinitionName)] internal class GoToDefinitionHandler : AbstractGoToDefinitionHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService) : base(metadataAsSourceFileService) { } public override string Method => LSP.Methods.TextDocumentDefinitionName; public override Task<LSP.Location[]> HandleRequestAsync(LSP.TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) => GetDefinitionAsync(request, typeOnly: false, context, cancellationToken); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/EditorFeatures/CSharpTest/EditAndContinue/LineEditTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class LineEditTests : EditingTestBase { #region Methods [Fact] public void Method_Reorder1() { var src1 = @" class C { static void Goo() { Console.ReadLine(1); } static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { Console.ReadLine(2); } static void Goo() { Console.ReadLine(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 9), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(7), new SourceLineUpdate(9, 4) }); } [Fact] public void Method_Reorder2() { var src1 = @" class Program { static void Main() { Goo(); Bar(); } static int Goo() { return 1; } static int Bar() { return 2; } }"; var src2 = @" class Program { static int Goo() { return 1; } static void Main() { Goo(); Bar(); } static int Bar() { return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 9), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(8), new SourceLineUpdate(10, 4), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(13), }); } [Fact] public void Method_Update() { var src1 = @" class C { static void Bar() { Console.ReadLine(1); } } "; var src2 = @" class C { static void Bar() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar")) }); } [Fact] public void Method_MultilineBreakpointSpans() { var src1 = @" class C { void F() { var x = 1; } } "; var src2 = @" class C { void F() { var x = 1; } }"; // We need to recompile the method since an active statement span [|var x = 1;|] // needs to be updated but can't be by a line update. var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }); } [Fact] public void Method_LineChange1() { var src1 = @" class C { static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 6) }); } [Fact] public void Method_LineChange2() { var src1 = @" class C { static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 5) }); } [Fact] public void Method_LineChange3() { var src1 = @" class C { static int X() => 1; static int Y() => 1; } "; var src2 = @" class C { static int X() => 1; static int Y() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(4) }); } [Fact] public void Method_Recompile1() { var src1 = @" class C { static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { /**/Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar")) }); } [Fact] public void Method_PartialBodyLineUpdate1() { var src1 = @" class C { static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(6, 5) }); } [Fact] public void Method_PartialBodyLineUpdate2() { var src1 = @" class C { static void Bar() /*1*/ { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { /*2*/ Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 4) }); } [Fact] public void Method_Recompile4() { var src1 = @" class C { static void Bar() { int <N:0.0>a = 1</N:0.0>; int <N:0.1>b = 2</N:0.1>; <AS:0>System.Console.WriteLine(1);</AS:0> } } "; var src2 = @" class C { static void Bar() { int <N:0.0>a = 1</N:0.0>; int <N:0.1>b = 2</N:0.1>; <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar")) }); var active = GetActiveStatements(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( active, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar"), syntaxMap[0]) }); } [Fact] public void Method_Recompile5() { var src1 = @" class C { static void Bar() { } } "; var src2 = @" class C { /*--*/static void Bar() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar")) }); } [Fact] public void Method_RudeRecompile1() { var src1 = @" class C<T> { static void Bar() { /*edit*/ Console.ReadLine(2); } } "; var src2 = @" class C<T> { static void Bar() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(6, 5) }); } [Fact] public void Method_RudeRecompile2() { var src1 = @" class C<T> { static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C<T> { static void Bar() { /*edit*/Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeTriviaUpdate, "\r\n /*edit*/", FeaturesResources.method) }); } [Fact] public void Method_RudeRecompile3() { var src1 = @" class C { static void Bar<T>() { /*edit*/Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar<T>() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "\r\n ", FeaturesResources.method) }); } [Fact] public void Method_RudeRecompile4() { var src1 = @" class C { static async Task<int> Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static async Task<int> Bar() { Console.ReadLine( 2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar"), preserveLocalVariables: true) }); } #endregion #region Constructors [Fact] public void Constructor_Reorder() { var src1 = @" class C { public C(int a) { } public C(bool a) { } } "; var src2 = @" class C { public C(bool a) { } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 8), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(6), new SourceLineUpdate(8, 4) }); } [Fact] public void Constructor_LineChange1() { var src1 = @" class C { public C(int a) : base() { } } "; var src2 = @" class C { public C(int a) : base() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 5) }); } [Fact] public void Constructor_ExpressionBodied_LineChange1() { var src1 = @" class C { int _a; public C(int a) => _a = a; } "; var src2 = @" class C { int _a; public C(int a) => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 6) }); } [Fact] public void Constructor_ExpressionBodied_LineChange2() { var src1 = @" class C { int _a; public C(int a) => _a = a; } "; var src2 = @" class C { int _a; public C(int a) => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 6) }); } [Fact] public void Constructor_ExpressionBodied_LineChange3() { var src1 = @" class C { int _a; public C(int a) => _a = a; } "; var src2 = @" class C { int _a; public C(int a) => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 6) }); } [Fact] public void Constructor_ExpressionBodied_LineChange4() { var src1 = @" class C { int _a; public C(int a) => _a = a; } "; var src2 = @" class C { int _a; public C(int a) => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(6, 8) }); } [Fact] public void Constructor_ExpressionBodiedWithBase_LineChange1() { var src1 = @" class C { int _a; public C(int a) : base() => _a = a; } "; var src2 = @" class C { int _a; public C(int a) : base() => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 6) }); } [Fact] public void Constructor_ExpressionBodiedWithBase_LineChange2() { var src1 = @" class C { int _a; public C(int a) : base() => _a = a; } "; var src2 = @" class C { int _a; public C(int a) : base() => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SourceLineUpdate[] { new(5, 6) }); } [Fact] public void Constructor_ExpressionBodiedWithBase_Recompile1() { var src1 = @" class C { int _a; public C(int a) : base() => _a = a; } "; var src2 = @" class C { int _a; public C(int a) : base() => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Constructor_PartialBodyLineChange1() { var src1 = @" class C { public C(int a) : base() { } } "; var src2 = @" class C { public C(int a) : base() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SourceLineUpdate[] { new(5, 6) }); } [Fact] public void Constructor_Recompile2() { var src1 = @" class C { public C(int a) : base() { } } "; var src2 = @" class C { public C(int a) : base() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Constructor_RudeRecompile1() { var src1 = @" class C<T> { public C(int a) : base() { } } "; var src2 = @" class C<T> { public C(int a) : base() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)") }); } #endregion #region Destructors [Fact] public void Destructor_LineChange1() { var src1 = @" class C { ~C() { } } "; var src2 = @" class C { ~C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 4) }); } [Fact] public void Destructor_ExpressionBodied_LineChange1() { var src1 = @" class C { ~C() => F(); } "; var src2 = @" class C { ~C() => F(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Destructor_ExpressionBodied_LineChange2() { var src1 = @" class C { ~C() => F(); } "; var src2 = @" class C { ~C() => F(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } #endregion #region Field Initializers [Fact] public void ConstantField() { var src1 = @" class C { const int Goo = 1; } "; var src2 = @" class C { const int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>()); } [Fact] public void NoInitializer() { var src1 = @" class C { int Goo; } "; var src2 = @" class C { int Goo; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>()); } [Fact] public void Field_Reorder() { var src1 = @" class C { static int Goo = 1; static int Bar = 2; } "; var src2 = @" class C { static int Bar = 2; static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.Move, "static int Bar = 2", FeaturesResources.field) }); } [Fact] public void Field_LineChange1() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 6) }); } [Fact] public void Field_LineChange2() { var src1 = @" class C { int Goo = 1, Bar = 2; } "; var src2 = @" class C { int Goo = 1, Bar = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_LineChange3() { var src1 = @" class C { [A]static int Goo = 1, Bar = 2; } "; var src2 = @" class C { [A] static int Goo = 1, Bar = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SourceLineUpdate[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Field_LineChange_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { int Goo = 1, Bar = 2; } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { int Goo = 1, Bar = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")) }); } [Fact] public void Field_Recompile1a() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Recompile1b() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Recompile1c() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Recompile1d() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Recompile1e() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1 ; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Recompile2() { var src1 = @" class C { static int Goo = 1 + 1; } "; var src2 = @" class C { static int Goo = 1 + 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_RudeRecompile2() { var src1 = @" class C<T> { static int Goo = 1 + 1; } "; var src2 = @" class C<T> { static int Goo = 1 + 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>") }); } [Fact] public void Field_Generic_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { static int Goo = 1 + 1; } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { static int Goo = 1 + 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")) }); } #endregion #region Properties [Fact] public void Property1() { var src1 = @" class C { int P { get { return 1; } } } "; var src2 = @" class C { int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod) }); } [Fact] public void Property2() { var src1 = @" class C { int P { get { return 1; } } } "; var src2 = @" class C { int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits(new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property3() { var src1 = @" class C { int P { get { return 1; } set { } } } "; var src2 = @" class C { int P { get { return 1; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_ExpressionBody1() { var src1 = @" class C { int P => 1; } "; var src2 = @" class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_GetterExpressionBody1() { var src1 = @" class C { int P { get => 1; } } "; var src2 = @" class C { int P { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_SetterExpressionBody1() { var src1 = @" class C { int P { set => F(); } } "; var src2 = @" class C { int P { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_Initializer1() { var src1 = @" class C { int P { get; } = 1; } "; var src2 = @" class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_Initializer2() { var src1 = @" class C { int P { get; } = 1; } "; var src2 = @" class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_Initializer3() { var src1 = @" class C { int P { get; } = 1; } "; var src2 = @" class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } #endregion #region Properties [Fact] public void Indexer1() { var src1 = @" class C { int this[int a] { get { return 1; } } } "; var src2 = @" class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.this[]").GetMethod) }); } [Fact] public void Indexer2() { var src1 = @" class C { int this[int a] { get { return 1; } } } "; var src2 = @" class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits(new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Indexer3() { var src1 = @" class C { int this[int a] { get { return 1; } set { } } } "; var src2 = @" class C { int this[int a] { get { return 1; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits(new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Indexer_ExpressionBody1() { var src1 = @" class C { int this[int a] => 1; } "; var src2 = @" class C { int this[int a] => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Indexer_GetterExpressionBody1() { var src1 = @" class C { int this[int a] { get => 1; } } "; var src2 = @" class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Indexer_SetterExpressionBody1() { var src1 = @" class C { int this[int a] { set => F(); } } "; var src2 = @" class C { int this[int a] { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } #endregion #region Events [Fact] public void Event_LineChange1() { var src1 = @" class C { event Action E { add { } remove { } } } "; var src2 = @" class C { event Action E { add { } remove { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void EventAdder_LineChangeAndRecompile1() { var src1 = @" class C { event Action E { add { } remove { } } } "; var src2 = @" class C { event Action E { add { } remove { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 3) }, semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.E").AddMethod) }); } [Fact] public void EventRemover_Recompile1() { var src1 = @" class C { event Action E { add { } remove { } } } "; var src2 = @" class C { event Action E { add { } remove { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.E").RemoveMethod) }); } [Fact] public void EventAdder_LineChange1() { var src1 = @" class C { event Action E { add { } remove { } } } "; var src2 = @" class C { event Action E { add { } remove { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 3) }); } [Fact] public void EventRemover_LineChange1() { var src1 = @" class C { event Action E { add { } remove { } } } "; var src2 = @" class C { event Action E { add { } remove { } } }"; // we can only apply one delta per line, but that would affect add and remove differently, so need to recompile var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.E").RemoveMethod) }); } [Fact, WorkItem(53263, "https://github.com/dotnet/roslyn/issues/53263")] public void Event_ExpressionBody_MultipleBodiesOnTheSameLine1() { var src1 = @" class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" class C { event Action E { add => F(); remove => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }, semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.E").RemoveMethod) }); } [Fact] public void Event_ExpressionBody() { var src1 = @" class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" class C { event Action E { add => F(); remove => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 3), new SourceLineUpdate(5, 3) }); } #endregion #region Types [Fact] public void Type_Reorder1() { var src1 = @" class C { static int F1() => 1; static int F2() => 1; } class D { static int G1() => 1; static int G2() => 1; } "; var src2 = @" class D { static int G1() => 1; static int G2() => 1; } class C { static int F1() => 1; static int F2() => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 9), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(5), new SourceLineUpdate(9, 3) }); } #endregion #region Line Mappings [Fact] public void LineMapping_ChangeLineNumber_WithinMethod_NoSequencePointImpact() { var src1 = @" class C { static void F() { G( #line 2 ""c"" 123 #line default ); } }"; var src2 = @" class C { static void F() { G( #line 3 ""c"" 123 #line default ); } }"; var edits = GetTopEdits(src1, src2); // Line deltas can't be applied on the whole breakpoint span hence recompilation. edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }); } /// <summary> /// Validates that changes in #line directives produce semantic updates of the containing method. /// </summary> [Fact] public void LineMapping_ChangeLineNumber_OutsideOfMethod() { var src1 = @" #line 1 ""a"" class C { int x = 1; static int y = 1; void F1() { } void F2() { } } class D { public D() {} #line 5 ""a"" void F3() {} #line 6 ""a"" void F4() {} }"; var src2 = @" #line 11 ""a"" class C { int x = 1; static int y = 1; void F1() { } void F2() { } } class D { public D() {} #line 5 ""a"" void F3() {} void F4() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SequencePointUpdates[] { new("a", ImmutableArray.Create<SourceLineUpdate>( new(2, 12), // x, y, F1, F2 AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(6), // lines between F2 and D ctor new(9, 19))) // D ctor }, semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.F3")), // overlaps with "void F1() { }" SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.F4")), // overlaps with "void F2() { }" }); } [Fact] public void LineMapping_LineDirectivesAndWhitespace() { var src1 = @" class C { #line 5 ""a"" #line 6 ""a"" static void F() { } // line 9 }"; var src2 = @" class C { #line 9 ""a"" static void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void LineMapping_MultipleFiles() { var src1 = @" class C { static void F() { #line 1 ""a"" A(); #line 1 ""b"" B(); #line default } }"; var src2 = @" class C { static void F() { #line 2 ""a"" A(); #line 2 ""b"" B(); #line default } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SequencePointUpdates[] { new("a", ImmutableArray.Create(new SourceLineUpdate(0, 1))), new("b", ImmutableArray.Create(new SourceLineUpdate(0, 1))), }); } [Fact] public void LineMapping_FileChange_Recompile() { var src1 = @" class C { static void F() { A(); #line 1 ""a"" B(); #line 3 ""a"" C(); } int x = 1; }"; var src2 = @" class C { static void F() { A(); #line 1 ""b"" B(); #line 2 ""a"" C(); } int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SequencePointUpdates[] { new("a", ImmutableArray.Create(new SourceLineUpdate(6, 4))), }, semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }); } [Fact] public void LineMapping_FileChange_RudeEdit() { var src1 = @" #line 1 ""a"" class C { static void Bar<T>() { } } "; var src2 = @" #line 1 ""b"" class C { static void Bar<T>() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "{", FeaturesResources.method) }); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class LineEditTests : EditingTestBase { #region Methods [Fact] public void Method_Reorder1() { var src1 = @" class C { static void Goo() { Console.ReadLine(1); } static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { Console.ReadLine(2); } static void Goo() { Console.ReadLine(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 9), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(7), new SourceLineUpdate(9, 4) }); } [Fact] public void Method_Reorder2() { var src1 = @" class Program { static void Main() { Goo(); Bar(); } static int Goo() { return 1; } static int Bar() { return 2; } }"; var src2 = @" class Program { static int Goo() { return 1; } static void Main() { Goo(); Bar(); } static int Bar() { return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 9), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(8), new SourceLineUpdate(10, 4), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(13), }); } [Fact] public void Method_Update() { var src1 = @" class C { static void Bar() { Console.ReadLine(1); } } "; var src2 = @" class C { static void Bar() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar")) }); } [Fact] public void Method_MultilineBreakpointSpans() { var src1 = @" class C { void F() { var x = 1; } } "; var src2 = @" class C { void F() { var x = 1; } }"; // We need to recompile the method since an active statement span [|var x = 1;|] // needs to be updated but can't be by a line update. var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }); } [Fact] public void Method_LineChange1() { var src1 = @" class C { static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 6) }); } [Fact] public void Method_LineChange2() { var src1 = @" class C { static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 5) }); } [Fact] public void Method_LineChange3() { var src1 = @" class C { static int X() => 1; static int Y() => 1; } "; var src2 = @" class C { static int X() => 1; static int Y() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(4) }); } [Fact] public void Method_Recompile1() { var src1 = @" class C { static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { /**/Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar")) }); } [Fact] public void Method_PartialBodyLineUpdate1() { var src1 = @" class C { static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(6, 5) }); } [Fact] public void Method_PartialBodyLineUpdate2() { var src1 = @" class C { static void Bar() /*1*/ { Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar() { /*2*/ Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 4) }); } [Fact] public void Method_Recompile4() { var src1 = @" class C { static void Bar() { int <N:0.0>a = 1</N:0.0>; int <N:0.1>b = 2</N:0.1>; <AS:0>System.Console.WriteLine(1);</AS:0> } } "; var src2 = @" class C { static void Bar() { int <N:0.0>a = 1</N:0.0>; int <N:0.1>b = 2</N:0.1>; <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar")) }); var active = GetActiveStatements(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( active, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar"), syntaxMap[0]) }); } [Fact] public void Method_Recompile5() { var src1 = @" class C { static void Bar() { } } "; var src2 = @" class C { /*--*/static void Bar() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar")) }); } [Fact] public void Method_RudeRecompile1() { var src1 = @" class C<T> { static void Bar() { /*edit*/ Console.ReadLine(2); } } "; var src2 = @" class C<T> { static void Bar() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(6, 5) }); } [Fact] public void Method_RudeRecompile2() { var src1 = @" class C<T> { static void Bar() { Console.ReadLine(2); } } "; var src2 = @" class C<T> { static void Bar() { /*edit*/Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeTriviaUpdate, "\r\n /*edit*/", FeaturesResources.method) }); } [Fact] public void Method_RudeRecompile3() { var src1 = @" class C { static void Bar<T>() { /*edit*/Console.ReadLine(2); } } "; var src2 = @" class C { static void Bar<T>() { Console.ReadLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "\r\n ", FeaturesResources.method) }); } [Fact] public void Method_RudeRecompile4() { var src1 = @" class C { static async Task<int> Bar() { Console.ReadLine(2); } } "; var src2 = @" class C { static async Task<int> Bar() { Console.ReadLine( 2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Bar"), preserveLocalVariables: true) }); } #endregion #region Constructors [Fact] public void Constructor_Reorder() { var src1 = @" class C { public C(int a) { } public C(bool a) { } } "; var src2 = @" class C { public C(bool a) { } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 8), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(6), new SourceLineUpdate(8, 4) }); } [Fact] public void Constructor_LineChange1() { var src1 = @" class C { public C(int a) : base() { } } "; var src2 = @" class C { public C(int a) : base() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 5) }); } [Fact] public void Constructor_ExpressionBodied_LineChange1() { var src1 = @" class C { int _a; public C(int a) => _a = a; } "; var src2 = @" class C { int _a; public C(int a) => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 6) }); } [Fact] public void Constructor_ExpressionBodied_LineChange2() { var src1 = @" class C { int _a; public C(int a) => _a = a; } "; var src2 = @" class C { int _a; public C(int a) => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 6) }); } [Fact] public void Constructor_ExpressionBodied_LineChange3() { var src1 = @" class C { int _a; public C(int a) => _a = a; } "; var src2 = @" class C { int _a; public C(int a) => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 6) }); } [Fact] public void Constructor_ExpressionBodied_LineChange4() { var src1 = @" class C { int _a; public C(int a) => _a = a; } "; var src2 = @" class C { int _a; public C(int a) => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(6, 8) }); } [Fact] public void Constructor_ExpressionBodiedWithBase_LineChange1() { var src1 = @" class C { int _a; public C(int a) : base() => _a = a; } "; var src2 = @" class C { int _a; public C(int a) : base() => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 6) }); } [Fact] public void Constructor_ExpressionBodiedWithBase_LineChange2() { var src1 = @" class C { int _a; public C(int a) : base() => _a = a; } "; var src2 = @" class C { int _a; public C(int a) : base() => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SourceLineUpdate[] { new(5, 6) }); } [Fact] public void Constructor_ExpressionBodiedWithBase_Recompile1() { var src1 = @" class C { int _a; public C(int a) : base() => _a = a; } "; var src2 = @" class C { int _a; public C(int a) : base() => _a = a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Constructor_PartialBodyLineChange1() { var src1 = @" class C { public C(int a) : base() { } } "; var src2 = @" class C { public C(int a) : base() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SourceLineUpdate[] { new(5, 6) }); } [Fact] public void Constructor_Recompile2() { var src1 = @" class C { public C(int a) : base() { } } "; var src2 = @" class C { public C(int a) : base() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Constructor_RudeRecompile1() { var src1 = @" class C<T> { public C(int a) : base() { } } "; var src2 = @" class C<T> { public C(int a) : base() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)") }); } #endregion #region Destructors [Fact] public void Destructor_LineChange1() { var src1 = @" class C { ~C() { } } "; var src2 = @" class C { ~C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(5, 4) }); } [Fact] public void Destructor_ExpressionBodied_LineChange1() { var src1 = @" class C { ~C() => F(); } "; var src2 = @" class C { ~C() => F(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Destructor_ExpressionBodied_LineChange2() { var src1 = @" class C { ~C() => F(); } "; var src2 = @" class C { ~C() => F(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } #endregion #region Field Initializers [Fact] public void ConstantField() { var src1 = @" class C { const int Goo = 1; } "; var src2 = @" class C { const int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>()); } [Fact] public void NoInitializer() { var src1 = @" class C { int Goo; } "; var src2 = @" class C { int Goo; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>()); } [Fact] public void Field_Reorder() { var src1 = @" class C { static int Goo = 1; static int Bar = 2; } "; var src2 = @" class C { static int Bar = 2; static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.Move, "static int Bar = 2", FeaturesResources.field) }); } [Fact] public void Field_LineChange1() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 6) }); } [Fact] public void Field_LineChange2() { var src1 = @" class C { int Goo = 1, Bar = 2; } "; var src2 = @" class C { int Goo = 1, Bar = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_LineChange3() { var src1 = @" class C { [A]static int Goo = 1, Bar = 2; } "; var src2 = @" class C { [A] static int Goo = 1, Bar = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SourceLineUpdate[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Field_LineChange_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { int Goo = 1, Bar = 2; } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { int Goo = 1, Bar = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")) }); } [Fact] public void Field_Recompile1a() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Recompile1b() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Recompile1c() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Recompile1d() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Recompile1e() { var src1 = @" class C { static int Goo = 1; } "; var src2 = @" class C { static int Goo = 1 ; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Recompile2() { var src1 = @" class C { static int Goo = 1 + 1; } "; var src2 = @" class C { static int Goo = 1 + 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_RudeRecompile2() { var src1 = @" class C<T> { static int Goo = 1 + 1; } "; var src2 = @" class C<T> { static int Goo = 1 + 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>") }); } [Fact] public void Field_Generic_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { static int Goo = 1 + 1; } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { static int Goo = 1 + 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")) }); } #endregion #region Properties [Fact] public void Property1() { var src1 = @" class C { int P { get { return 1; } } } "; var src2 = @" class C { int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod) }); } [Fact] public void Property2() { var src1 = @" class C { int P { get { return 1; } } } "; var src2 = @" class C { int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits(new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property3() { var src1 = @" class C { int P { get { return 1; } set { } } } "; var src2 = @" class C { int P { get { return 1; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_ExpressionBody1() { var src1 = @" class C { int P => 1; } "; var src2 = @" class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_GetterExpressionBody1() { var src1 = @" class C { int P { get => 1; } } "; var src2 = @" class C { int P { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_SetterExpressionBody1() { var src1 = @" class C { int P { set => F(); } } "; var src2 = @" class C { int P { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_Initializer1() { var src1 = @" class C { int P { get; } = 1; } "; var src2 = @" class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_Initializer2() { var src1 = @" class C { int P { get; } = 1; } "; var src2 = @" class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Property_Initializer3() { var src1 = @" class C { int P { get; } = 1; } "; var src2 = @" class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } #endregion #region Properties [Fact] public void Indexer1() { var src1 = @" class C { int this[int a] { get { return 1; } } } "; var src2 = @" class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.this[]").GetMethod) }); } [Fact] public void Indexer2() { var src1 = @" class C { int this[int a] { get { return 1; } } } "; var src2 = @" class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits(new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Indexer3() { var src1 = @" class C { int this[int a] { get { return 1; } set { } } } "; var src2 = @" class C { int this[int a] { get { return 1; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits(new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Indexer_ExpressionBody1() { var src1 = @" class C { int this[int a] => 1; } "; var src2 = @" class C { int this[int a] => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Indexer_GetterExpressionBody1() { var src1 = @" class C { int this[int a] { get => 1; } } "; var src2 = @" class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void Indexer_SetterExpressionBody1() { var src1 = @" class C { int this[int a] { set => F(); } } "; var src2 = @" class C { int this[int a] { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } #endregion #region Events [Fact] public void Event_LineChange1() { var src1 = @" class C { event Action E { add { } remove { } } } "; var src2 = @" class C { event Action E { add { } remove { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }); } [Fact] public void EventAdder_LineChangeAndRecompile1() { var src1 = @" class C { event Action E { add { } remove { } } } "; var src2 = @" class C { event Action E { add { } remove { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 3) }, semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.E").AddMethod) }); } [Fact] public void EventRemover_Recompile1() { var src1 = @" class C { event Action E { add { } remove { } } } "; var src2 = @" class C { event Action E { add { } remove { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.E").RemoveMethod) }); } [Fact] public void EventAdder_LineChange1() { var src1 = @" class C { event Action E { add { } remove { } } } "; var src2 = @" class C { event Action E { add { } remove { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 3) }); } [Fact] public void EventRemover_LineChange1() { var src1 = @" class C { event Action E { add { } remove { } } } "; var src2 = @" class C { event Action E { add { } remove { } } }"; // we can only apply one delta per line, but that would affect add and remove differently, so need to recompile var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.E").RemoveMethod) }); } [Fact, WorkItem(53263, "https://github.com/dotnet/roslyn/issues/53263")] public void Event_ExpressionBody_MultipleBodiesOnTheSameLine1() { var src1 = @" class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" class C { event Action E { add => F(); remove => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 4) }, semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.E").RemoveMethod) }); } [Fact] public void Event_ExpressionBody() { var src1 = @" class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" class C { event Action E { add => F(); remove => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(4, 3), new SourceLineUpdate(5, 3) }); } #endregion #region Types [Fact] public void Type_Reorder1() { var src1 = @" class C { static int F1() => 1; static int F2() => 1; } class D { static int G1() => 1; static int G2() => 1; } "; var src2 = @" class D { static int G1() => 1; static int G2() => 1; } class C { static int F1() => 1; static int F2() => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new[] { new SourceLineUpdate(3, 9), AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(5), new SourceLineUpdate(9, 3) }); } #endregion #region Line Mappings [Fact] public void LineMapping_ChangeLineNumber_WithinMethod_NoSequencePointImpact() { var src1 = @" class C { static void F() { G( #line 2 ""c"" 123 #line default ); } }"; var src2 = @" class C { static void F() { G( #line 3 ""c"" 123 #line default ); } }"; var edits = GetTopEdits(src1, src2); // Line deltas can't be applied on the whole breakpoint span hence recompilation. edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }); } /// <summary> /// Validates that changes in #line directives produce semantic updates of the containing method. /// </summary> [Fact] public void LineMapping_ChangeLineNumber_OutsideOfMethod() { var src1 = @" #line 1 ""a"" class C { int x = 1; static int y = 1; void F1() { } void F2() { } } class D { public D() {} #line 5 ""a"" void F3() {} #line 6 ""a"" void F4() {} }"; var src2 = @" #line 11 ""a"" class C { int x = 1; static int y = 1; void F1() { } void F2() { } } class D { public D() {} #line 5 ""a"" void F3() {} void F4() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SequencePointUpdates[] { new("a", ImmutableArray.Create<SourceLineUpdate>( new(2, 12), // x, y, F1, F2 AbstractEditAndContinueAnalyzer.CreateZeroDeltaSourceLineUpdate(6), // lines between F2 and D ctor new(9, 19))) // D ctor }, semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.F3")), // overlaps with "void F1() { }" SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.F4")), // overlaps with "void F2() { }" }); } [Fact] public void LineMapping_LineDirectivesAndWhitespace() { var src1 = @" class C { #line 5 ""a"" #line 6 ""a"" static void F() { } // line 9 }"; var src2 = @" class C { #line 9 ""a"" static void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void LineMapping_MultipleFiles() { var src1 = @" class C { static void F() { #line 1 ""a"" A(); #line 1 ""b"" B(); #line default } }"; var src2 = @" class C { static void F() { #line 2 ""a"" A(); #line 2 ""b"" B(); #line default } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SequencePointUpdates[] { new("a", ImmutableArray.Create(new SourceLineUpdate(0, 1))), new("b", ImmutableArray.Create(new SourceLineUpdate(0, 1))), }); } [Fact] public void LineMapping_FileChange_Recompile() { var src1 = @" class C { static void F() { A(); #line 1 ""a"" B(); #line 3 ""a"" C(); } int x = 1; }"; var src2 = @" class C { static void F() { A(); #line 1 ""b"" B(); #line 2 ""a"" C(); } int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( new SequencePointUpdates[] { new("a", ImmutableArray.Create(new SourceLineUpdate(6, 4))), }, semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }); } [Fact] public void LineMapping_FileChange_RudeEdit() { var src1 = @" #line 1 ""a"" class C { static void Bar<T>() { } } "; var src2 = @" #line 1 ""b"" class C { static void Bar<T>() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyLineEdits( Array.Empty<SequencePointUpdates>(), diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "{", FeaturesResources.method) }); } #endregion } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextGetAdjustSpacesOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] internal readonly struct NextGetAdjustSpacesOperation { private readonly ImmutableArray<AbstractFormattingRule> _formattingRules; private readonly int _index; public NextGetAdjustSpacesOperation( ImmutableArray<AbstractFormattingRule> formattingRules, int index) { _formattingRules = formattingRules; _index = index; } private NextGetAdjustSpacesOperation NextOperation => new(_formattingRules, _index + 1); public AdjustSpacesOperation? Invoke(in SyntaxToken previousToken, in SyntaxToken currentToken) { // If we have no remaining handlers to execute, then we'll execute our last handler if (_index >= _formattingRules.Length) { return null; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 return _formattingRules[_index].GetAdjustSpacesOperation(in previousToken, in currentToken, NextOperation); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] internal readonly struct NextGetAdjustSpacesOperation { private readonly ImmutableArray<AbstractFormattingRule> _formattingRules; private readonly int _index; public NextGetAdjustSpacesOperation( ImmutableArray<AbstractFormattingRule> formattingRules, int index) { _formattingRules = formattingRules; _index = index; } private NextGetAdjustSpacesOperation NextOperation => new(_formattingRules, _index + 1); public AdjustSpacesOperation? Invoke(in SyntaxToken previousToken, in SyntaxToken currentToken) { // If we have no remaining handlers to execute, then we'll execute our last handler if (_index >= _formattingRules.Length) { return null; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 return _formattingRules[_index].GetAdjustSpacesOperation(in previousToken, in currentToken, NextOperation); } } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/CSharp/Portable/CodeRefactorings/ConvertLocalFunctionToMethod/CSharpConvertLocalFunctionToMethodCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ConvertLocalFunctionToMethod { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertLocalFunctionToMethod), Shared] internal sealed class CSharpConvertLocalFunctionToMethodCodeRefactoringProvider : CodeRefactoringProvider { private static readonly SyntaxAnnotation s_delegateToReplaceAnnotation = new SyntaxAnnotation(); private static readonly SyntaxGenerator s_generator = CSharpSyntaxGenerator.Instance; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertLocalFunctionToMethodCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var localFunction = await context.TryGetRelevantNodeAsync<LocalFunctionStatementSyntax>().ConfigureAwait(false); if (localFunction == null) { return; } if (!localFunction.Parent.IsKind(SyntaxKind.Block, out BlockSyntax parentBlock)) { return; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); context.RegisterRefactoring( new MyCodeAction( c => UpdateDocumentAsync(root, document, parentBlock, localFunction, c)), localFunction.Span); } private static async Task<Document> UpdateDocumentAsync( SyntaxNode root, Document document, BlockSyntax parentBlock, LocalFunctionStatementSyntax localFunction, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declaredSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(localFunction, cancellationToken); var dataFlow = semanticModel.AnalyzeDataFlow( localFunction.Body ?? (SyntaxNode)localFunction.ExpressionBody.Expression); // Exclude local function parameters in case they were captured inside the function body var captures = dataFlow.CapturedInside.Except(dataFlow.VariablesDeclared).Except(declaredSymbol.Parameters).ToList(); // First, create a parameter per each capture so that we can pass them as arguments to the final method // Filter out `this` because it doesn't need a parameter, we will just make a non-static method for that // We also make a `ref` parameter here for each capture that is being written into inside the function var capturesAsParameters = captures .Where(capture => !capture.IsThisParameter()) .Select(capture => CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: dataFlow.WrittenInside.Contains(capture) ? RefKind.Ref : RefKind.None, isParams: false, type: capture.GetSymbolType(), name: capture.Name)).ToList(); // Find all enclosing type parameters e.g. from outer local functions and the containing member // We exclude the containing type itself which has type parameters accessible to all members var typeParameters = new List<ITypeParameterSymbol>(); GetCapturedTypeParameters(declaredSymbol, typeParameters); // We're going to remove unreferenced type parameters but we explicitly preserve // captures' types, just in case that they were not spelt out in the function body var captureTypes = captures.SelectMany(capture => capture.GetSymbolType().GetReferencedTypeParameters()); RemoveUnusedTypeParameters(localFunction, semanticModel, typeParameters, reservedTypeParameters: captureTypes); var container = localFunction.GetAncestor<MemberDeclarationSyntax>(); var containerSymbol = semanticModel.GetDeclaredSymbol(container, cancellationToken); var isStatic = containerSymbol.IsStatic || captures.All(capture => !capture.IsThisParameter()); // GetSymbolModifiers actually checks if the local function needs to be unsafe, not whether // it is declared as such, so this check we don't need to worry about whether the containing method // is unsafe, this will just work regardless. var needsUnsafe = declaredSymbol.GetSymbolModifiers().IsUnsafe; var methodName = GenerateUniqueMethodName(declaredSymbol); var parameters = declaredSymbol.Parameters; var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( containingType: declaredSymbol.ContainingType, attributes: default, accessibility: Accessibility.Private, modifiers: new DeclarationModifiers(isStatic, isAsync: declaredSymbol.IsAsync, isUnsafe: needsUnsafe), returnType: declaredSymbol.ReturnType, refKind: default, explicitInterfaceImplementations: default, name: methodName, typeParameters: typeParameters.ToImmutableArray(), parameters: parameters.AddRange(capturesAsParameters)); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var defaultOptions = new CodeGenerationOptions(options: options); var method = MethodGenerator.GenerateMethodDeclaration(methodSymbol, CodeGenerationDestination.Unspecified, defaultOptions, root.SyntaxTree.Options); var generator = s_generator; var editor = new SyntaxEditor(root, generator); var needsRename = methodName != declaredSymbol.Name; var identifierToken = needsRename ? methodName.ToIdentifierToken() : default; var supportsNonTrailing = SupportsNonTrailingNamedArguments(root.SyntaxTree.Options); var hasAdditionalArguments = !capturesAsParameters.IsEmpty(); var additionalTypeParameters = typeParameters.Except(declaredSymbol.TypeParameters).ToList(); var hasAdditionalTypeArguments = !additionalTypeParameters.IsEmpty(); var additionalTypeArguments = hasAdditionalTypeArguments ? additionalTypeParameters.Select(p => (TypeSyntax)p.Name.ToIdentifierName()).ToArray() : null; var anyDelegatesToReplace = false; // Update callers' name, arguments and type arguments foreach (var node in parentBlock.DescendantNodes()) { // A local function reference can only be an identifier or a generic name. switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: break; default: continue; } // Using symbol to get type arguments, since it could be inferred and not present in the source var symbol = semanticModel.GetSymbolInfo(node, cancellationToken).Symbol as IMethodSymbol; if (!Equals(symbol?.OriginalDefinition, declaredSymbol)) { continue; } var currentNode = node; if (needsRename) { currentNode = ((SimpleNameSyntax)currentNode).WithIdentifier(identifierToken); } if (hasAdditionalTypeArguments) { var existingTypeArguments = symbol.TypeArguments.Select(s => s.GenerateTypeSyntax()); // Prepend additional type arguments to preserve lexical order in which they are defined var typeArguments = additionalTypeArguments.Concat(existingTypeArguments); currentNode = generator.WithTypeArguments(currentNode, typeArguments); currentNode = currentNode.WithAdditionalAnnotations(Simplifier.Annotation); } if (node.Parent.IsKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax invocation)) { if (hasAdditionalArguments) { var shouldUseNamedArguments = !supportsNonTrailing && invocation.ArgumentList.Arguments.Any(arg => arg.NameColon != null); var additionalArguments = capturesAsParameters.Select(p => (ArgumentSyntax)GenerateArgument(p, p.Name, shouldUseNamedArguments)).ToArray(); editor.ReplaceNode(invocation.ArgumentList, invocation.ArgumentList.AddArguments(additionalArguments)); } } else if (hasAdditionalArguments || hasAdditionalTypeArguments) { // Convert local function delegates to lambda if the signature no longer matches currentNode = currentNode.WithAdditionalAnnotations(s_delegateToReplaceAnnotation); anyDelegatesToReplace = true; } editor.ReplaceNode(node, currentNode); } editor.TrackNode(localFunction); editor.TrackNode(container); root = editor.GetChangedRoot(); localFunction = root.GetCurrentNode(localFunction); container = root.GetCurrentNode(container); method = WithBodyFrom(method, localFunction); editor = new SyntaxEditor(root, generator); editor.InsertAfter(container, method); editor.RemoveNode(localFunction, SyntaxRemoveOptions.KeepNoTrivia); if (anyDelegatesToReplace) { document = document.WithSyntaxRoot(editor.GetChangedRoot()); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); editor = new SyntaxEditor(root, generator); foreach (var node in root.GetAnnotatedNodes(s_delegateToReplaceAnnotation)) { var reservedNames = GetReservedNames(node, semanticModel, cancellationToken); var parameterNames = GenerateUniqueParameterNames(parameters, reservedNames); var lambdaParameters = parameters.Zip(parameterNames, (p, name) => GenerateParameter(p, name)); var lambdaArguments = parameters.Zip(parameterNames, (p, name) => GenerateArgument(p, name)); var additionalArguments = capturesAsParameters.Select(p => GenerateArgument(p, p.Name)); var newNode = generator.ValueReturningLambdaExpression(lambdaParameters, generator.InvocationExpression(node, lambdaArguments.Concat(additionalArguments))); newNode = newNode.WithAdditionalAnnotations(Simplifier.Annotation); if (node.IsParentKind(SyntaxKind.CastExpression)) { newNode = ((ExpressionSyntax)newNode).Parenthesize(); } editor.ReplaceNode(node, newNode); } } return document.WithSyntaxRoot(editor.GetChangedRoot()); } private static bool SupportsNonTrailingNamedArguments(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7_2; private static SyntaxNode GenerateArgument(IParameterSymbol p, string name, bool shouldUseNamedArguments = false) => s_generator.Argument(shouldUseNamedArguments ? name : null, p.RefKind, name.ToIdentifierName()); private static List<string> GenerateUniqueParameterNames(ImmutableArray<IParameterSymbol> parameters, List<string> reservedNames) => parameters.Select(p => NameGenerator.EnsureUniqueness(p.Name, reservedNames)).ToList(); private static List<string> GetReservedNames(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) => semanticModel.GetAllDeclaredSymbols(node.GetAncestor<MemberDeclarationSyntax>(), cancellationToken).Select(s => s.Name).ToList(); private static ParameterSyntax GenerateParameter(IParameterSymbol p, string name) { return SyntaxFactory.Parameter(name.ToIdentifierToken()) .WithModifiers(CSharpSyntaxGeneratorInternal.GetParameterModifiers(p.RefKind)) .WithType(p.Type.GenerateTypeSyntax()); } private static MethodDeclarationSyntax WithBodyFrom( MethodDeclarationSyntax method, LocalFunctionStatementSyntax localFunction) { return method .WithExpressionBody(localFunction.ExpressionBody) .WithSemicolonToken(localFunction.SemicolonToken) .WithBody(localFunction.Body); } private static void GetCapturedTypeParameters(ISymbol symbol, List<ITypeParameterSymbol> typeParameters) { var containingSymbol = symbol.ContainingSymbol; if (containingSymbol != null && containingSymbol.Kind != SymbolKind.NamedType) { GetCapturedTypeParameters(containingSymbol, typeParameters); } typeParameters.AddRange(symbol.GetTypeParameters()); } private static void RemoveUnusedTypeParameters( SyntaxNode localFunction, SemanticModel semanticModel, List<ITypeParameterSymbol> typeParameters, IEnumerable<ITypeParameterSymbol> reservedTypeParameters) { var unusedTypeParameters = typeParameters.ToList(); foreach (var id in localFunction.DescendantNodes().OfType<IdentifierNameSyntax>()) { var symbol = semanticModel.GetSymbolInfo(id).Symbol; if (symbol != null && symbol.OriginalDefinition is ITypeParameterSymbol typeParameter) { unusedTypeParameters.Remove(typeParameter); } } typeParameters.RemoveRange(unusedTypeParameters.Except(reservedTypeParameters)); } private static string GenerateUniqueMethodName(ISymbol declaredSymbol) { return NameGenerator.EnsureUniqueness( baseName: declaredSymbol.Name, reservedNames: declaredSymbol.ContainingType.GetMembers().Select(m => m.Name)); } private sealed class MyCodeAction : CodeActions.CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Convert_to_method, createChangedDocument, nameof(CSharpFeaturesResources.Convert_to_method)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ConvertLocalFunctionToMethod { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertLocalFunctionToMethod), Shared] internal sealed class CSharpConvertLocalFunctionToMethodCodeRefactoringProvider : CodeRefactoringProvider { private static readonly SyntaxAnnotation s_delegateToReplaceAnnotation = new SyntaxAnnotation(); private static readonly SyntaxGenerator s_generator = CSharpSyntaxGenerator.Instance; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertLocalFunctionToMethodCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var localFunction = await context.TryGetRelevantNodeAsync<LocalFunctionStatementSyntax>().ConfigureAwait(false); if (localFunction == null) { return; } if (!localFunction.Parent.IsKind(SyntaxKind.Block, out BlockSyntax parentBlock)) { return; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); context.RegisterRefactoring( new MyCodeAction( c => UpdateDocumentAsync(root, document, parentBlock, localFunction, c)), localFunction.Span); } private static async Task<Document> UpdateDocumentAsync( SyntaxNode root, Document document, BlockSyntax parentBlock, LocalFunctionStatementSyntax localFunction, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declaredSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(localFunction, cancellationToken); var dataFlow = semanticModel.AnalyzeDataFlow( localFunction.Body ?? (SyntaxNode)localFunction.ExpressionBody.Expression); // Exclude local function parameters in case they were captured inside the function body var captures = dataFlow.CapturedInside.Except(dataFlow.VariablesDeclared).Except(declaredSymbol.Parameters).ToList(); // First, create a parameter per each capture so that we can pass them as arguments to the final method // Filter out `this` because it doesn't need a parameter, we will just make a non-static method for that // We also make a `ref` parameter here for each capture that is being written into inside the function var capturesAsParameters = captures .Where(capture => !capture.IsThisParameter()) .Select(capture => CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: dataFlow.WrittenInside.Contains(capture) ? RefKind.Ref : RefKind.None, isParams: false, type: capture.GetSymbolType(), name: capture.Name)).ToList(); // Find all enclosing type parameters e.g. from outer local functions and the containing member // We exclude the containing type itself which has type parameters accessible to all members var typeParameters = new List<ITypeParameterSymbol>(); GetCapturedTypeParameters(declaredSymbol, typeParameters); // We're going to remove unreferenced type parameters but we explicitly preserve // captures' types, just in case that they were not spelt out in the function body var captureTypes = captures.SelectMany(capture => capture.GetSymbolType().GetReferencedTypeParameters()); RemoveUnusedTypeParameters(localFunction, semanticModel, typeParameters, reservedTypeParameters: captureTypes); var container = localFunction.GetAncestor<MemberDeclarationSyntax>(); var containerSymbol = semanticModel.GetDeclaredSymbol(container, cancellationToken); var isStatic = containerSymbol.IsStatic || captures.All(capture => !capture.IsThisParameter()); // GetSymbolModifiers actually checks if the local function needs to be unsafe, not whether // it is declared as such, so this check we don't need to worry about whether the containing method // is unsafe, this will just work regardless. var needsUnsafe = declaredSymbol.GetSymbolModifiers().IsUnsafe; var methodName = GenerateUniqueMethodName(declaredSymbol); var parameters = declaredSymbol.Parameters; var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( containingType: declaredSymbol.ContainingType, attributes: default, accessibility: Accessibility.Private, modifiers: new DeclarationModifiers(isStatic, isAsync: declaredSymbol.IsAsync, isUnsafe: needsUnsafe), returnType: declaredSymbol.ReturnType, refKind: default, explicitInterfaceImplementations: default, name: methodName, typeParameters: typeParameters.ToImmutableArray(), parameters: parameters.AddRange(capturesAsParameters)); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var defaultOptions = new CodeGenerationOptions(options: options); var method = MethodGenerator.GenerateMethodDeclaration(methodSymbol, CodeGenerationDestination.Unspecified, defaultOptions, root.SyntaxTree.Options); var generator = s_generator; var editor = new SyntaxEditor(root, generator); var needsRename = methodName != declaredSymbol.Name; var identifierToken = needsRename ? methodName.ToIdentifierToken() : default; var supportsNonTrailing = SupportsNonTrailingNamedArguments(root.SyntaxTree.Options); var hasAdditionalArguments = !capturesAsParameters.IsEmpty(); var additionalTypeParameters = typeParameters.Except(declaredSymbol.TypeParameters).ToList(); var hasAdditionalTypeArguments = !additionalTypeParameters.IsEmpty(); var additionalTypeArguments = hasAdditionalTypeArguments ? additionalTypeParameters.Select(p => (TypeSyntax)p.Name.ToIdentifierName()).ToArray() : null; var anyDelegatesToReplace = false; // Update callers' name, arguments and type arguments foreach (var node in parentBlock.DescendantNodes()) { // A local function reference can only be an identifier or a generic name. switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: break; default: continue; } // Using symbol to get type arguments, since it could be inferred and not present in the source var symbol = semanticModel.GetSymbolInfo(node, cancellationToken).Symbol as IMethodSymbol; if (!Equals(symbol?.OriginalDefinition, declaredSymbol)) { continue; } var currentNode = node; if (needsRename) { currentNode = ((SimpleNameSyntax)currentNode).WithIdentifier(identifierToken); } if (hasAdditionalTypeArguments) { var existingTypeArguments = symbol.TypeArguments.Select(s => s.GenerateTypeSyntax()); // Prepend additional type arguments to preserve lexical order in which they are defined var typeArguments = additionalTypeArguments.Concat(existingTypeArguments); currentNode = generator.WithTypeArguments(currentNode, typeArguments); currentNode = currentNode.WithAdditionalAnnotations(Simplifier.Annotation); } if (node.Parent.IsKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax invocation)) { if (hasAdditionalArguments) { var shouldUseNamedArguments = !supportsNonTrailing && invocation.ArgumentList.Arguments.Any(arg => arg.NameColon != null); var additionalArguments = capturesAsParameters.Select(p => (ArgumentSyntax)GenerateArgument(p, p.Name, shouldUseNamedArguments)).ToArray(); editor.ReplaceNode(invocation.ArgumentList, invocation.ArgumentList.AddArguments(additionalArguments)); } } else if (hasAdditionalArguments || hasAdditionalTypeArguments) { // Convert local function delegates to lambda if the signature no longer matches currentNode = currentNode.WithAdditionalAnnotations(s_delegateToReplaceAnnotation); anyDelegatesToReplace = true; } editor.ReplaceNode(node, currentNode); } editor.TrackNode(localFunction); editor.TrackNode(container); root = editor.GetChangedRoot(); localFunction = root.GetCurrentNode(localFunction); container = root.GetCurrentNode(container); method = WithBodyFrom(method, localFunction); editor = new SyntaxEditor(root, generator); editor.InsertAfter(container, method); editor.RemoveNode(localFunction, SyntaxRemoveOptions.KeepNoTrivia); if (anyDelegatesToReplace) { document = document.WithSyntaxRoot(editor.GetChangedRoot()); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); editor = new SyntaxEditor(root, generator); foreach (var node in root.GetAnnotatedNodes(s_delegateToReplaceAnnotation)) { var reservedNames = GetReservedNames(node, semanticModel, cancellationToken); var parameterNames = GenerateUniqueParameterNames(parameters, reservedNames); var lambdaParameters = parameters.Zip(parameterNames, (p, name) => GenerateParameter(p, name)); var lambdaArguments = parameters.Zip(parameterNames, (p, name) => GenerateArgument(p, name)); var additionalArguments = capturesAsParameters.Select(p => GenerateArgument(p, p.Name)); var newNode = generator.ValueReturningLambdaExpression(lambdaParameters, generator.InvocationExpression(node, lambdaArguments.Concat(additionalArguments))); newNode = newNode.WithAdditionalAnnotations(Simplifier.Annotation); if (node.IsParentKind(SyntaxKind.CastExpression)) { newNode = ((ExpressionSyntax)newNode).Parenthesize(); } editor.ReplaceNode(node, newNode); } } return document.WithSyntaxRoot(editor.GetChangedRoot()); } private static bool SupportsNonTrailingNamedArguments(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7_2; private static SyntaxNode GenerateArgument(IParameterSymbol p, string name, bool shouldUseNamedArguments = false) => s_generator.Argument(shouldUseNamedArguments ? name : null, p.RefKind, name.ToIdentifierName()); private static List<string> GenerateUniqueParameterNames(ImmutableArray<IParameterSymbol> parameters, List<string> reservedNames) => parameters.Select(p => NameGenerator.EnsureUniqueness(p.Name, reservedNames)).ToList(); private static List<string> GetReservedNames(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) => semanticModel.GetAllDeclaredSymbols(node.GetAncestor<MemberDeclarationSyntax>(), cancellationToken).Select(s => s.Name).ToList(); private static ParameterSyntax GenerateParameter(IParameterSymbol p, string name) { return SyntaxFactory.Parameter(name.ToIdentifierToken()) .WithModifiers(CSharpSyntaxGeneratorInternal.GetParameterModifiers(p.RefKind)) .WithType(p.Type.GenerateTypeSyntax()); } private static MethodDeclarationSyntax WithBodyFrom( MethodDeclarationSyntax method, LocalFunctionStatementSyntax localFunction) { return method .WithExpressionBody(localFunction.ExpressionBody) .WithSemicolonToken(localFunction.SemicolonToken) .WithBody(localFunction.Body); } private static void GetCapturedTypeParameters(ISymbol symbol, List<ITypeParameterSymbol> typeParameters) { var containingSymbol = symbol.ContainingSymbol; if (containingSymbol != null && containingSymbol.Kind != SymbolKind.NamedType) { GetCapturedTypeParameters(containingSymbol, typeParameters); } typeParameters.AddRange(symbol.GetTypeParameters()); } private static void RemoveUnusedTypeParameters( SyntaxNode localFunction, SemanticModel semanticModel, List<ITypeParameterSymbol> typeParameters, IEnumerable<ITypeParameterSymbol> reservedTypeParameters) { var unusedTypeParameters = typeParameters.ToList(); foreach (var id in localFunction.DescendantNodes().OfType<IdentifierNameSyntax>()) { var symbol = semanticModel.GetSymbolInfo(id).Symbol; if (symbol != null && symbol.OriginalDefinition is ITypeParameterSymbol typeParameter) { unusedTypeParameters.Remove(typeParameter); } } typeParameters.RemoveRange(unusedTypeParameters.Except(reservedTypeParameters)); } private static string GenerateUniqueMethodName(ISymbol declaredSymbol) { return NameGenerator.EnsureUniqueness( baseName: declaredSymbol.Name, reservedNames: declaredSymbol.ContainingType.GetMembers().Select(m => m.Name)); } private sealed class MyCodeAction : CodeActions.CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Convert_to_method, createChangedDocument, nameof(CSharpFeaturesResources.Convert_to_method)) { } } } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/VisualStudio/Xaml/Impl/Features/TypeRename/IXamlTypeRenameService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.TypeRename { internal interface IXamlTypeRenameService : ILanguageService { public Task<XamlTypeRenameResult> GetTypeRenameAsync(TextDocument document, int position, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.TypeRename { internal interface IXamlTypeRenameService : ILanguageService { public Task<XamlTypeRenameResult> GetTypeRenameAsync(TextDocument document, int position, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/VisualBasic/Portable/Structure/Providers/ObjectCreationInitializerStructureProvider.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.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class ObjectCreationInitializerStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of ObjectCreationInitializerSyntax) Protected Overrides Sub CollectBlockSpans(node As ObjectCreationInitializerSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) ' ObjectCreationInitializerSyntax is either "With { ... }" or "From { ... }" ' Parent Is something Like ' ' New Dictionary(Of int, string) From { ' ... ' } ' ' The collapsed textspan should be from the ) to the } ' ' However, the hint span should be the entire object creation. Dim previousToken = node.GetFirstToken().GetPreviousToken() spans.Add(New BlockSpan( isCollapsible:=True, textSpan:=TextSpan.FromBounds(previousToken.Span.End, node.Span.End), hintSpan:=node.Parent.Span, type:=BlockTypes.Expression)) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class ObjectCreationInitializerStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of ObjectCreationInitializerSyntax) Protected Overrides Sub CollectBlockSpans(node As ObjectCreationInitializerSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) ' ObjectCreationInitializerSyntax is either "With { ... }" or "From { ... }" ' Parent Is something Like ' ' New Dictionary(Of int, string) From { ' ... ' } ' ' The collapsed textspan should be from the ) to the } ' ' However, the hint span should be the entire object creation. Dim previousToken = node.GetFirstToken().GetPreviousToken() spans.Add(New BlockSpan( isCollapsible:=True, textSpan:=TextSpan.FromBounds(previousToken.Span.End, node.Span.End), hintSpan:=node.Parent.Span, type:=BlockTypes.Expression)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/VisualStudio/Core/Def/ValueTracking/ValueTrackingTreeViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Media; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class ValueTrackingTreeViewModel : INotifyPropertyChanged { private Brush? _highlightBrush; public Brush? HighlightBrush { get => _highlightBrush; set => SetProperty(ref _highlightBrush, value); } public IClassificationFormatMap ClassificationFormatMap { get; } public ClassificationTypeMap ClassificationTypeMap { get; } public IEditorFormatMapService FormatMapService { get; } public ObservableCollection<TreeItemViewModel> Roots { get; } = new(); private TreeViewItemBase? _selectedItem; public TreeViewItemBase? SelectedItem { get => _selectedItem; set => SetProperty(ref _selectedItem, value); } private string _selectedItemFile = ""; public string SelectedItemFile { get => _selectedItemFile; set => SetProperty(ref _selectedItemFile, value); } private int _selectedItemLine; public int SelectedItemLine { get => _selectedItemLine; set => SetProperty(ref _selectedItemLine, value); } private bool _isLoading; public bool IsLoading { get => _isLoading; private set => SetProperty(ref _isLoading, value); } private int _loadingCount; public int LoadingCount { get => _loadingCount; set => SetProperty(ref _loadingCount, value); } public bool ShowDetails => SelectedItem is TreeItemViewModel; public event PropertyChangedEventHandler? PropertyChanged; public ValueTrackingTreeViewModel(IClassificationFormatMap classificationFormatMap, ClassificationTypeMap classificationTypeMap, IEditorFormatMapService formatMapService) { ClassificationFormatMap = classificationFormatMap; ClassificationTypeMap = classificationTypeMap; FormatMapService = formatMapService; var editorMap = FormatMapService.GetEditorFormatMap("text"); SetHighlightBrush(editorMap); editorMap.FormatMappingChanged += (s, e) => { SetHighlightBrush(editorMap); }; PropertyChanged += Self_PropertyChanged; } private void SetHighlightBrush(IEditorFormatMap editorMap) { var properties = editorMap.GetProperties(ReferenceHighlightTag.TagId); HighlightBrush = properties["Background"] as Brush; } private void Self_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(SelectedItem)) { if (SelectedItem is not null) { SelectedItem.IsNodeSelected = true; if (SelectedItem is TreeItemViewModel itemWithInfo) { SelectedItemFile = itemWithInfo?.FileName ?? ""; SelectedItemLine = itemWithInfo?.LineNumber ?? 0; } else { SelectedItemFile = string.Empty; SelectedItemLine = 0; } } NotifyPropertyChanged(nameof(ShowDetails)); } if (e.PropertyName == nameof(LoadingCount)) { IsLoading = LoadingCount > 0; } } private void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = "") { if (EqualityComparer<T>.Default.Equals(field, value)) { return; } field = value; NotifyPropertyChanged(name); } private void NotifyPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Media; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class ValueTrackingTreeViewModel : INotifyPropertyChanged { private Brush? _highlightBrush; public Brush? HighlightBrush { get => _highlightBrush; set => SetProperty(ref _highlightBrush, value); } public IClassificationFormatMap ClassificationFormatMap { get; } public ClassificationTypeMap ClassificationTypeMap { get; } public IEditorFormatMapService FormatMapService { get; } public ObservableCollection<TreeItemViewModel> Roots { get; } = new(); private TreeViewItemBase? _selectedItem; public TreeViewItemBase? SelectedItem { get => _selectedItem; set => SetProperty(ref _selectedItem, value); } private string _selectedItemFile = ""; public string SelectedItemFile { get => _selectedItemFile; set => SetProperty(ref _selectedItemFile, value); } private int _selectedItemLine; public int SelectedItemLine { get => _selectedItemLine; set => SetProperty(ref _selectedItemLine, value); } private bool _isLoading; public bool IsLoading { get => _isLoading; private set => SetProperty(ref _isLoading, value); } private int _loadingCount; public int LoadingCount { get => _loadingCount; set => SetProperty(ref _loadingCount, value); } public bool ShowDetails => SelectedItem is TreeItemViewModel; public event PropertyChangedEventHandler? PropertyChanged; public ValueTrackingTreeViewModel(IClassificationFormatMap classificationFormatMap, ClassificationTypeMap classificationTypeMap, IEditorFormatMapService formatMapService) { ClassificationFormatMap = classificationFormatMap; ClassificationTypeMap = classificationTypeMap; FormatMapService = formatMapService; var editorMap = FormatMapService.GetEditorFormatMap("text"); SetHighlightBrush(editorMap); editorMap.FormatMappingChanged += (s, e) => { SetHighlightBrush(editorMap); }; PropertyChanged += Self_PropertyChanged; } private void SetHighlightBrush(IEditorFormatMap editorMap) { var properties = editorMap.GetProperties(ReferenceHighlightTag.TagId); HighlightBrush = properties["Background"] as Brush; } private void Self_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(SelectedItem)) { if (SelectedItem is not null) { SelectedItem.IsNodeSelected = true; if (SelectedItem is TreeItemViewModel itemWithInfo) { SelectedItemFile = itemWithInfo?.FileName ?? ""; SelectedItemLine = itemWithInfo?.LineNumber ?? 0; } else { SelectedItemFile = string.Empty; SelectedItemLine = 0; } } NotifyPropertyChanged(nameof(ShowDetails)); } if (e.PropertyName == nameof(LoadingCount)) { IsLoading = LoadingCount > 0; } } private void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = "") { if (EqualityComparer<T>.Default.Equals(field, value)) { return; } field = value; NotifyPropertyChanged(name); } private void NotifyPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Diagnostics/IBuiltInAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// This interface is a marker for all the analyzers that are built in. /// We will record non-fatal-watson if any analyzer with this interface throws an exception. /// /// also, built in analyzer can do things that third-party analyzer (command line analyzer) can't do /// such as reporting all diagnostic descriptors as hidden when it can return different severity on runtime. /// /// or reporting diagnostics ID that is not reported by SupportedDiagnostics. /// /// this interface is used by the engine to allow this special behavior over command line analyzers. /// </summary> internal interface IBuiltInAnalyzer { /// <summary> /// This category will be used to run analyzer more efficiently by restricting scope of analysis /// </summary> DiagnosticAnalyzerCategory GetAnalyzerCategory(); /// <summary> /// This indicates whether this built-in analyzer will only run on opened files. /// </summary> bool OpenFileOnly(OptionSet options); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// This interface is a marker for all the analyzers that are built in. /// We will record non-fatal-watson if any analyzer with this interface throws an exception. /// /// also, built in analyzer can do things that third-party analyzer (command line analyzer) can't do /// such as reporting all diagnostic descriptors as hidden when it can return different severity on runtime. /// /// or reporting diagnostics ID that is not reported by SupportedDiagnostics. /// /// this interface is used by the engine to allow this special behavior over command line analyzers. /// </summary> internal interface IBuiltInAnalyzer { /// <summary> /// This category will be used to run analyzer more efficiently by restricting scope of analysis /// </summary> DiagnosticAnalyzerCategory GetAnalyzerCategory(); /// <summary> /// This indicates whether this built-in analyzer will only run on opened files. /// </summary> bool OpenFileOnly(OptionSet options); } }
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousTypeOrDelegateTypeParameterSymbol.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.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Private NotInheritable Class AnonymousTypeOrDelegateTypeParameterSymbol Inherits TypeParameterSymbol Private ReadOnly _container As AnonymousTypeOrDelegateTemplateSymbol Private ReadOnly _ordinal As Integer Public Sub New(container As AnonymousTypeOrDelegateTemplateSymbol, ordinal As Integer) _container = container _ordinal = ordinal End Sub Public Overrides ReadOnly Property TypeParameterKind As TypeParameterKind Get Return TypeParameterKind.Type End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Friend Overrides ReadOnly Property ConstraintTypesNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol) Get Return ImmutableArray(Of TypeSymbol).Empty End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides ReadOnly Property Name As String Get If _container.TypeKind = TypeKind.Delegate Then If _container.DelegateInvokeMethod.IsSub OrElse Ordinal < _container.Arity - 1 Then Return "TArg" & Ordinal Else Return "TResult" End If Else Debug.Assert(_container.TypeKind = TypeKind.Class) Return "T" & Ordinal End If End Get End Property Public Overrides ReadOnly Property Ordinal As Integer Get Return _ordinal End Get End Property Public Overrides ReadOnly Property HasConstructorConstraint As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property HasReferenceTypeConstraint As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property HasValueTypeConstraint As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Variance As VarianceKind Get Return VarianceKind.None End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property Friend Overrides Sub EnsureAllConstraintsAreResolved() End Sub Public Overrides Function GetHashCode() As Integer Return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(Me) End Function Public Overrides Function Equals(other As TypeSymbol, comparison As TypeCompareKind) As Boolean Return other Is Me End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Private NotInheritable Class AnonymousTypeOrDelegateTypeParameterSymbol Inherits TypeParameterSymbol Private ReadOnly _container As AnonymousTypeOrDelegateTemplateSymbol Private ReadOnly _ordinal As Integer Public Sub New(container As AnonymousTypeOrDelegateTemplateSymbol, ordinal As Integer) _container = container _ordinal = ordinal End Sub Public Overrides ReadOnly Property TypeParameterKind As TypeParameterKind Get Return TypeParameterKind.Type End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Friend Overrides ReadOnly Property ConstraintTypesNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol) Get Return ImmutableArray(Of TypeSymbol).Empty End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides ReadOnly Property Name As String Get If _container.TypeKind = TypeKind.Delegate Then If _container.DelegateInvokeMethod.IsSub OrElse Ordinal < _container.Arity - 1 Then Return "TArg" & Ordinal Else Return "TResult" End If Else Debug.Assert(_container.TypeKind = TypeKind.Class) Return "T" & Ordinal End If End Get End Property Public Overrides ReadOnly Property Ordinal As Integer Get Return _ordinal End Get End Property Public Overrides ReadOnly Property HasConstructorConstraint As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property HasReferenceTypeConstraint As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property HasValueTypeConstraint As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Variance As VarianceKind Get Return VarianceKind.None End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property Friend Overrides Sub EnsureAllConstraintsAreResolved() End Sub Public Overrides Function GetHashCode() As Integer Return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(Me) End Function Public Overrides Function Equals(other As TypeSymbol, comparison As TypeCompareKind) As Boolean Return other Is Me End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/VisualBasic/Portable/CodeFixes/IncorrectExitContinue/IncorrectExitContinueCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.IncorrectExitContinue <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.FixIncorrectExitContinue), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.ImplementInterface)> Partial Friend Class IncorrectExitContinueCodeFixProvider Inherits CodeFixProvider Friend Const BC30781 As String = "BC30781" ' 'Continue' must be followed by 'Do', 'For' or 'While'. Friend Const BC30782 As String = "BC30782" ' 'Continue Do' can only appear inside a 'Do' statement. Friend Const BC30783 As String = "BC30783" ' 'Continue For' can only appear inside a 'For' statement. Friend Const BC30784 As String = "BC30784" ' 'Continue While' can only appear inside a 'While' statement. Friend Const BC30240 As String = "BC30240" ' 'Exit' must be followed by 'Sub', 'Function', 'Property', 'Do', 'For', 'While', 'Select', or 'Try'. Friend Const BC30065 As String = "BC30065" ' 'Exit Sub' is not valid in a Function or Property. Friend Const BC30066 As String = "BC30066" ' 'Exit Property' is not valid in a Function or Sub. Friend Const BC30067 As String = "BC30067" ' 'Exit Function' is not valid in a Sub or Property. Friend Const BC30089 As String = "BC30089" ' 'Exit Do' can only appear inside a 'Do' statement. Friend Const BC30096 As String = "BC30096" ' 'Exit For' can only appear inside a 'For' statement. Friend Const BC30097 As String = "BC30097" ' 'Exit While' can only appear inside a 'While' statement. Friend Const BC30099 As String = "BC30099" ' 'Exit Select' can only appear inside a 'Select' statement. Friend Const BC30393 As String = "BC30393" ' 'Exit Try' can only appear inside a 'Try' statement. Friend Const BC30689 As String = "BC30689" ' Statement cannot appear outside of a method body. <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 Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return ImmutableArray.Create(BC30781, BC30782, BC30783, BC30784, BC30240, BC30065, BC30066, BC30067, BC30089, BC30096, BC30097, BC30099, BC30393, BC30689) End Get End Property Public Overrides Function GetFixAllProvider() As FixAllProvider ' Fix All is not supported for this code fix ' https://github.com/dotnet/roslyn/issues/34466 Return Nothing End Function Public NotOverridable Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task Dim document = context.Document Dim span = context.Span Dim cancellationToken = context.CancellationToken Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim token = root.FindToken(span.Start) If Not token.Span.IntersectsWith(span) Then Return End If Dim node = token.GetAncestors(Of SyntaxNode) _ .FirstOrDefault(Function(c) Return c.Span.IntersectsWith(span) AndAlso ( TypeOf (c) Is ContinueStatementSyntax OrElse TypeOf (c) Is ExitStatementSyntax) End Function) If node Is Nothing Then Return End If Dim enclosingblocks = node.GetContainingExecutableBlocks() If Not enclosingblocks.Any() Then context.RegisterCodeFix(New RemoveStatementCodeAction(document, node, CreateDeleteString(node)), context.Diagnostics) Return End If Dim codeActions As List(Of CodeAction) = Nothing Dim semanticDoc = Await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(False) CreateExitCodeActions(semanticDoc, node, enclosingblocks, codeActions, cancellationToken) CreateContinueCodeActions(semanticDoc, node, enclosingblocks, codeActions, cancellationToken) context.RegisterFixes(codeActions, context.Diagnostics) End Function Private Sub CreateContinueCodeActions(document As SemanticDocument, node As SyntaxNode, enclosingblocks As IEnumerable(Of SyntaxNode), ByRef codeActions As List(Of CodeAction), cancellationToken As CancellationToken) Dim continueStatement = TryCast(node, ContinueStatementSyntax) If continueStatement IsNot Nothing Then Dim enclosingDeclaration = document.SemanticModel.GetEnclosingSymbol(node.SpanStart, cancellationToken) If enclosingDeclaration Is Nothing Then Return End If If codeActions Is Nothing Then codeActions = New List(Of CodeAction) End If Dim blockKinds = GetEnclosingContinuableBlockKinds(enclosingblocks) Dim tokenAfterContinueToken = continueStatement.ContinueKeyword.GetNextToken(includeSkipped:=True) Dim text = document.Text If continueStatement.BlockKeyword.IsMissing Then If tokenAfterContinueToken.IsSkipped() AndAlso text.Lines.IndexOf(tokenAfterContinueToken.SpanStart) = text.Lines.IndexOf(continueStatement.SpanStart) Then CreateReplaceTokenKeywordActions(blockKinds, tokenAfterContinueToken, document.Document, codeActions) Else CreateAddKeywordActions(continueStatement, document.Document, enclosingblocks.First(), blockKinds, AddressOf CreateContinueStatement, codeActions) codeActions.Add(New RemoveStatementCodeAction(document.Document, continueStatement, CreateDeleteString(continueStatement))) End If ElseIf Not blockKinds.Any(Function(bk) KeywordAndBlockKindMatch(bk, continueStatement.BlockKeyword.Kind)) Then CreateReplaceKeywordActions(blockKinds, tokenAfterContinueToken, continueStatement, enclosingblocks.First(), document.Document, AddressOf CreateContinueStatement, codeActions) codeActions.Add(New RemoveStatementCodeAction(document.Document, continueStatement, CreateDeleteString(continueStatement))) End If End If End Sub Private Sub CreateExitCodeActions(document As SemanticDocument, node As SyntaxNode, enclosingblocks As IEnumerable(Of SyntaxNode), ByRef codeActions As List(Of CodeAction), cancellationToken As CancellationToken) Dim exitStatement = TryCast(node, ExitStatementSyntax) If exitStatement IsNot Nothing Then Dim enclosingDeclaration = document.SemanticModel.GetEnclosingSymbol(node.SpanStart, cancellationToken) If enclosingDeclaration Is Nothing Then Return End If If codeActions Is Nothing Then codeActions = New List(Of CodeAction) End If Dim blockKinds = GetEnclosingBlockKinds(enclosingblocks, enclosingDeclaration) Dim tokenAfterExitToken = exitStatement.ExitKeyword.GetNextToken(includeSkipped:=True) Dim text = document.Text If exitStatement.BlockKeyword.IsMissing Then If tokenAfterExitToken.IsSkipped() AndAlso text.Lines.IndexOf(tokenAfterExitToken.SpanStart) = text.Lines.IndexOf(exitStatement.SpanStart) Then CreateReplaceTokenKeywordActions(blockKinds, tokenAfterExitToken, document.Document, codeActions) Else CreateAddKeywordActions(exitStatement, document.Document, enclosingblocks.First(), blockKinds, AddressOf CreateExitStatement, codeActions) codeActions.Add(New RemoveStatementCodeAction(document.Document, exitStatement, CreateDeleteString(exitStatement))) End If ElseIf Not blockKinds.Any(Function(bk) KeywordAndBlockKindMatch(bk, exitStatement.BlockKeyword.Kind)) Then CreateReplaceKeywordActions(blockKinds, tokenAfterExitToken, exitStatement, enclosingblocks.First(), document.Document, AddressOf CreateExitStatement, codeActions) codeActions.Add(New RemoveStatementCodeAction(document.Document, exitStatement, CreateDeleteString(exitStatement))) End If End If End Sub Private Shared Function GetEnclosingBlockKinds(enclosingblocks As IEnumerable(Of SyntaxNode), enclosingDeclaration As ISymbol) As IEnumerable(Of SyntaxKind) Dim kinds = New List(Of SyntaxKind)(enclosingblocks.Select(Function(b) b.Kind()).Where(Function(kind) BlockKindToKeywordKind(kind) <> Nothing OrElse kind = SyntaxKind.FinallyBlock)) ' If we're inside a method declaration, we can only exit if it's a Function/Sub (lambda) or a property set or get. Dim methodSymbol = TryCast(enclosingDeclaration, IMethodSymbol) If methodSymbol IsNot Nothing Then If methodSymbol.MethodKind = MethodKind.PropertyGet Then kinds.Add(SyntaxKind.GetAccessorBlock) ElseIf methodSymbol.MethodKind = MethodKind.PropertySet Then kinds.Add(SyntaxKind.SetAccessorBlock) ElseIf methodSymbol.ReturnsVoid() Then kinds.Add(SyntaxKind.SubBlock) Else kinds.Add(SyntaxKind.FunctionBlock) End If End If ' For each enclosing-before-finally block, select block kinds that won't generate duplicate keyword kinds. Return kinds.TakeWhile(Function(k) k <> SyntaxKind.FinallyBlock).GroupBy(Function(k) BlockKindToKeywordKind(k)).Select(Function(g) g.First()) End Function Private Shared Function GetEnclosingContinuableBlockKinds(enclosingblocks As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SyntaxKind) Return enclosingblocks.TakeWhile(Function(eb) eb.Kind() <> SyntaxKind.FinallyBlock) _ .Where(Function(eb) eb.IsKind(SyntaxKind.WhileBlock, SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock, SyntaxKind.ForBlock, SyntaxKind.ForEachBlock)) _ .Select(Function(eb) eb.Kind()) _ .Distinct() End Function Private Function CreateExitStatement(exitSyntax As SyntaxNode, containingBlock As SyntaxNode, createBlockKind As SyntaxKind, document As Document, cancellationToken As CancellationToken) As StatementSyntax Dim exitStatement = DirectCast(exitSyntax, ExitStatementSyntax) Dim keywordKind = BlockKindToKeywordKind(createBlockKind) Dim statementKind = BlockKindToStatementKind(createBlockKind) Dim newToken = SyntaxFactory.Token(keywordKind) _ .WithLeadingTrivia(exitStatement.BlockKeyword.LeadingTrivia) _ .WithTrailingTrivia(exitStatement.BlockKeyword.TrailingTrivia) Dim updatedSyntax = SyntaxFactory.ExitStatement(statementKind, newToken) _ .WithLeadingTrivia(exitStatement.GetLeadingTrivia()) _ .WithTrailingTrivia(exitStatement.GetTrailingTrivia()) _ .WithAdditionalAnnotations(Formatter.Annotation) Return updatedSyntax End Function Private Function CreateContinueStatement(continueSyntax As SyntaxNode, containingBlock As SyntaxNode, createBlockKind As SyntaxKind, document As Document, cancellationToken As CancellationToken) As StatementSyntax Dim keywordKind = BlockKindToKeywordKind(createBlockKind) Dim statementKind = BlockKindToContinuableStatementKind(createBlockKind) Dim continueStatement = DirectCast(continueSyntax, ContinueStatementSyntax) Dim newToken = SyntaxFactory.Token(keywordKind) _ .WithLeadingTrivia(continueStatement.BlockKeyword.LeadingTrivia) _ .WithTrailingTrivia(continueStatement.BlockKeyword.TrailingTrivia) Dim updatedSyntax = SyntaxFactory.ContinueStatement(statementKind, newToken) _ .WithLeadingTrivia(continueStatement.GetLeadingTrivia()) _ .WithTrailingTrivia(continueStatement.GetTrailingTrivia()) _ .WithAdditionalAnnotations(Formatter.Annotation) Return updatedSyntax End Function Private Shared Function KeywordAndBlockKindMatch(blockKind As SyntaxKind, keywordKind As SyntaxKind) As Boolean Return keywordKind = BlockKindToKeywordKind(blockKind) End Function Private Shared Function BlockKindToKeywordKind(blockKind As SyntaxKind) As SyntaxKind Select Case blockKind Case SyntaxKind.WhileBlock Return SyntaxKind.WhileKeyword Case SyntaxKind.TryBlock, SyntaxKind.CatchBlock Return SyntaxKind.TryKeyword Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock Return SyntaxKind.DoKeyword Case SyntaxKind.ForBlock, SyntaxKind.ForEachBlock Return SyntaxKind.ForKeyword Case SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock Return SyntaxKind.SelectKeyword Case SyntaxKind.SubBlock Return SyntaxKind.SubKeyword Case SyntaxKind.FunctionBlock Return SyntaxKind.FunctionKeyword Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock Return SyntaxKind.PropertyKeyword Case Else Return Nothing End Select End Function Private Shared Function BlockKindToStatementKind(blockKind As SyntaxKind) As SyntaxKind Select Case blockKind Case SyntaxKind.WhileBlock Return SyntaxKind.ExitWhileStatement Case SyntaxKind.TryBlock, SyntaxKind.CatchBlock Return SyntaxKind.ExitTryStatement Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock Return SyntaxKind.ExitDoStatement Case SyntaxKind.ForBlock, SyntaxKind.ForEachBlock Return SyntaxKind.ExitForStatement Case SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock Return SyntaxKind.ExitSelectStatement Case SyntaxKind.SubBlock Return SyntaxKind.ExitSubStatement Case SyntaxKind.FunctionBlock Return SyntaxKind.ExitFunctionStatement Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock Return SyntaxKind.ExitPropertyStatement Case Else Throw ExceptionUtilities.UnexpectedValue(blockKind) End Select End Function Private Shared Function BlockKindToContinuableStatementKind(blockKind As SyntaxKind) As SyntaxKind Select Case blockKind Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock Return SyntaxKind.ContinueDoStatement Case SyntaxKind.ForBlock, SyntaxKind.ForEachBlock Return SyntaxKind.ContinueForStatement Case SyntaxKind.WhileBlock Return SyntaxKind.ContinueWhileStatement Case Else Throw ExceptionUtilities.UnexpectedValue(blockKind) End Select End Function Private Shared Sub CreateAddKeywordActions(node As SyntaxNode, document As Document, enclosingBlock As SyntaxNode, blockKinds As IEnumerable(Of SyntaxKind), updateNode As Func(Of SyntaxNode, SyntaxNode, SyntaxKind, Document, CancellationToken, StatementSyntax), codeActions As IList(Of CodeAction)) codeActions.AddRange(blockKinds.Select(Function(bk) New AddKeywordCodeAction(node, bk, enclosingBlock, document, updateNode))) End Sub Private Shared Sub CreateReplaceKeywordActions(blockKinds As IEnumerable(Of SyntaxKind), invalidToken As SyntaxToken, node As SyntaxNode, enclosingBlock As SyntaxNode, document As Document, updateNode As Func(Of SyntaxNode, SyntaxNode, SyntaxKind, Document, CancellationToken, StatementSyntax), codeActions As IList(Of CodeAction)) codeActions.AddRange(blockKinds.Select(Function(bk) New ReplaceKeywordCodeAction(bk, invalidToken, node, enclosingBlock, document, updateNode))) End Sub Private Shared Sub CreateReplaceTokenKeywordActions(blockKinds As IEnumerable(Of SyntaxKind), invalidToken As SyntaxToken, document As Document, codeActions As List(Of CodeAction)) codeActions.AddRange(blockKinds.Select(Function(bk) New ReplaceTokenKeywordCodeAction(bk, invalidToken, document))) End Sub Private Shared Function CreateDeleteString(node As SyntaxNode) As String Return String.Format(VBFeaturesResources.Delete_the_0_statement1, node.ToString().Trim()) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.IncorrectExitContinue <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.FixIncorrectExitContinue), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.ImplementInterface)> Partial Friend Class IncorrectExitContinueCodeFixProvider Inherits CodeFixProvider Friend Const BC30781 As String = "BC30781" ' 'Continue' must be followed by 'Do', 'For' or 'While'. Friend Const BC30782 As String = "BC30782" ' 'Continue Do' can only appear inside a 'Do' statement. Friend Const BC30783 As String = "BC30783" ' 'Continue For' can only appear inside a 'For' statement. Friend Const BC30784 As String = "BC30784" ' 'Continue While' can only appear inside a 'While' statement. Friend Const BC30240 As String = "BC30240" ' 'Exit' must be followed by 'Sub', 'Function', 'Property', 'Do', 'For', 'While', 'Select', or 'Try'. Friend Const BC30065 As String = "BC30065" ' 'Exit Sub' is not valid in a Function or Property. Friend Const BC30066 As String = "BC30066" ' 'Exit Property' is not valid in a Function or Sub. Friend Const BC30067 As String = "BC30067" ' 'Exit Function' is not valid in a Sub or Property. Friend Const BC30089 As String = "BC30089" ' 'Exit Do' can only appear inside a 'Do' statement. Friend Const BC30096 As String = "BC30096" ' 'Exit For' can only appear inside a 'For' statement. Friend Const BC30097 As String = "BC30097" ' 'Exit While' can only appear inside a 'While' statement. Friend Const BC30099 As String = "BC30099" ' 'Exit Select' can only appear inside a 'Select' statement. Friend Const BC30393 As String = "BC30393" ' 'Exit Try' can only appear inside a 'Try' statement. Friend Const BC30689 As String = "BC30689" ' Statement cannot appear outside of a method body. <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 Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return ImmutableArray.Create(BC30781, BC30782, BC30783, BC30784, BC30240, BC30065, BC30066, BC30067, BC30089, BC30096, BC30097, BC30099, BC30393, BC30689) End Get End Property Public Overrides Function GetFixAllProvider() As FixAllProvider ' Fix All is not supported for this code fix ' https://github.com/dotnet/roslyn/issues/34466 Return Nothing End Function Public NotOverridable Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task Dim document = context.Document Dim span = context.Span Dim cancellationToken = context.CancellationToken Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim token = root.FindToken(span.Start) If Not token.Span.IntersectsWith(span) Then Return End If Dim node = token.GetAncestors(Of SyntaxNode) _ .FirstOrDefault(Function(c) Return c.Span.IntersectsWith(span) AndAlso ( TypeOf (c) Is ContinueStatementSyntax OrElse TypeOf (c) Is ExitStatementSyntax) End Function) If node Is Nothing Then Return End If Dim enclosingblocks = node.GetContainingExecutableBlocks() If Not enclosingblocks.Any() Then context.RegisterCodeFix(New RemoveStatementCodeAction(document, node, CreateDeleteString(node)), context.Diagnostics) Return End If Dim codeActions As List(Of CodeAction) = Nothing Dim semanticDoc = Await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(False) CreateExitCodeActions(semanticDoc, node, enclosingblocks, codeActions, cancellationToken) CreateContinueCodeActions(semanticDoc, node, enclosingblocks, codeActions, cancellationToken) context.RegisterFixes(codeActions, context.Diagnostics) End Function Private Sub CreateContinueCodeActions(document As SemanticDocument, node As SyntaxNode, enclosingblocks As IEnumerable(Of SyntaxNode), ByRef codeActions As List(Of CodeAction), cancellationToken As CancellationToken) Dim continueStatement = TryCast(node, ContinueStatementSyntax) If continueStatement IsNot Nothing Then Dim enclosingDeclaration = document.SemanticModel.GetEnclosingSymbol(node.SpanStart, cancellationToken) If enclosingDeclaration Is Nothing Then Return End If If codeActions Is Nothing Then codeActions = New List(Of CodeAction) End If Dim blockKinds = GetEnclosingContinuableBlockKinds(enclosingblocks) Dim tokenAfterContinueToken = continueStatement.ContinueKeyword.GetNextToken(includeSkipped:=True) Dim text = document.Text If continueStatement.BlockKeyword.IsMissing Then If tokenAfterContinueToken.IsSkipped() AndAlso text.Lines.IndexOf(tokenAfterContinueToken.SpanStart) = text.Lines.IndexOf(continueStatement.SpanStart) Then CreateReplaceTokenKeywordActions(blockKinds, tokenAfterContinueToken, document.Document, codeActions) Else CreateAddKeywordActions(continueStatement, document.Document, enclosingblocks.First(), blockKinds, AddressOf CreateContinueStatement, codeActions) codeActions.Add(New RemoveStatementCodeAction(document.Document, continueStatement, CreateDeleteString(continueStatement))) End If ElseIf Not blockKinds.Any(Function(bk) KeywordAndBlockKindMatch(bk, continueStatement.BlockKeyword.Kind)) Then CreateReplaceKeywordActions(blockKinds, tokenAfterContinueToken, continueStatement, enclosingblocks.First(), document.Document, AddressOf CreateContinueStatement, codeActions) codeActions.Add(New RemoveStatementCodeAction(document.Document, continueStatement, CreateDeleteString(continueStatement))) End If End If End Sub Private Sub CreateExitCodeActions(document As SemanticDocument, node As SyntaxNode, enclosingblocks As IEnumerable(Of SyntaxNode), ByRef codeActions As List(Of CodeAction), cancellationToken As CancellationToken) Dim exitStatement = TryCast(node, ExitStatementSyntax) If exitStatement IsNot Nothing Then Dim enclosingDeclaration = document.SemanticModel.GetEnclosingSymbol(node.SpanStart, cancellationToken) If enclosingDeclaration Is Nothing Then Return End If If codeActions Is Nothing Then codeActions = New List(Of CodeAction) End If Dim blockKinds = GetEnclosingBlockKinds(enclosingblocks, enclosingDeclaration) Dim tokenAfterExitToken = exitStatement.ExitKeyword.GetNextToken(includeSkipped:=True) Dim text = document.Text If exitStatement.BlockKeyword.IsMissing Then If tokenAfterExitToken.IsSkipped() AndAlso text.Lines.IndexOf(tokenAfterExitToken.SpanStart) = text.Lines.IndexOf(exitStatement.SpanStart) Then CreateReplaceTokenKeywordActions(blockKinds, tokenAfterExitToken, document.Document, codeActions) Else CreateAddKeywordActions(exitStatement, document.Document, enclosingblocks.First(), blockKinds, AddressOf CreateExitStatement, codeActions) codeActions.Add(New RemoveStatementCodeAction(document.Document, exitStatement, CreateDeleteString(exitStatement))) End If ElseIf Not blockKinds.Any(Function(bk) KeywordAndBlockKindMatch(bk, exitStatement.BlockKeyword.Kind)) Then CreateReplaceKeywordActions(blockKinds, tokenAfterExitToken, exitStatement, enclosingblocks.First(), document.Document, AddressOf CreateExitStatement, codeActions) codeActions.Add(New RemoveStatementCodeAction(document.Document, exitStatement, CreateDeleteString(exitStatement))) End If End If End Sub Private Shared Function GetEnclosingBlockKinds(enclosingblocks As IEnumerable(Of SyntaxNode), enclosingDeclaration As ISymbol) As IEnumerable(Of SyntaxKind) Dim kinds = New List(Of SyntaxKind)(enclosingblocks.Select(Function(b) b.Kind()).Where(Function(kind) BlockKindToKeywordKind(kind) <> Nothing OrElse kind = SyntaxKind.FinallyBlock)) ' If we're inside a method declaration, we can only exit if it's a Function/Sub (lambda) or a property set or get. Dim methodSymbol = TryCast(enclosingDeclaration, IMethodSymbol) If methodSymbol IsNot Nothing Then If methodSymbol.MethodKind = MethodKind.PropertyGet Then kinds.Add(SyntaxKind.GetAccessorBlock) ElseIf methodSymbol.MethodKind = MethodKind.PropertySet Then kinds.Add(SyntaxKind.SetAccessorBlock) ElseIf methodSymbol.ReturnsVoid() Then kinds.Add(SyntaxKind.SubBlock) Else kinds.Add(SyntaxKind.FunctionBlock) End If End If ' For each enclosing-before-finally block, select block kinds that won't generate duplicate keyword kinds. Return kinds.TakeWhile(Function(k) k <> SyntaxKind.FinallyBlock).GroupBy(Function(k) BlockKindToKeywordKind(k)).Select(Function(g) g.First()) End Function Private Shared Function GetEnclosingContinuableBlockKinds(enclosingblocks As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SyntaxKind) Return enclosingblocks.TakeWhile(Function(eb) eb.Kind() <> SyntaxKind.FinallyBlock) _ .Where(Function(eb) eb.IsKind(SyntaxKind.WhileBlock, SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock, SyntaxKind.ForBlock, SyntaxKind.ForEachBlock)) _ .Select(Function(eb) eb.Kind()) _ .Distinct() End Function Private Function CreateExitStatement(exitSyntax As SyntaxNode, containingBlock As SyntaxNode, createBlockKind As SyntaxKind, document As Document, cancellationToken As CancellationToken) As StatementSyntax Dim exitStatement = DirectCast(exitSyntax, ExitStatementSyntax) Dim keywordKind = BlockKindToKeywordKind(createBlockKind) Dim statementKind = BlockKindToStatementKind(createBlockKind) Dim newToken = SyntaxFactory.Token(keywordKind) _ .WithLeadingTrivia(exitStatement.BlockKeyword.LeadingTrivia) _ .WithTrailingTrivia(exitStatement.BlockKeyword.TrailingTrivia) Dim updatedSyntax = SyntaxFactory.ExitStatement(statementKind, newToken) _ .WithLeadingTrivia(exitStatement.GetLeadingTrivia()) _ .WithTrailingTrivia(exitStatement.GetTrailingTrivia()) _ .WithAdditionalAnnotations(Formatter.Annotation) Return updatedSyntax End Function Private Function CreateContinueStatement(continueSyntax As SyntaxNode, containingBlock As SyntaxNode, createBlockKind As SyntaxKind, document As Document, cancellationToken As CancellationToken) As StatementSyntax Dim keywordKind = BlockKindToKeywordKind(createBlockKind) Dim statementKind = BlockKindToContinuableStatementKind(createBlockKind) Dim continueStatement = DirectCast(continueSyntax, ContinueStatementSyntax) Dim newToken = SyntaxFactory.Token(keywordKind) _ .WithLeadingTrivia(continueStatement.BlockKeyword.LeadingTrivia) _ .WithTrailingTrivia(continueStatement.BlockKeyword.TrailingTrivia) Dim updatedSyntax = SyntaxFactory.ContinueStatement(statementKind, newToken) _ .WithLeadingTrivia(continueStatement.GetLeadingTrivia()) _ .WithTrailingTrivia(continueStatement.GetTrailingTrivia()) _ .WithAdditionalAnnotations(Formatter.Annotation) Return updatedSyntax End Function Private Shared Function KeywordAndBlockKindMatch(blockKind As SyntaxKind, keywordKind As SyntaxKind) As Boolean Return keywordKind = BlockKindToKeywordKind(blockKind) End Function Private Shared Function BlockKindToKeywordKind(blockKind As SyntaxKind) As SyntaxKind Select Case blockKind Case SyntaxKind.WhileBlock Return SyntaxKind.WhileKeyword Case SyntaxKind.TryBlock, SyntaxKind.CatchBlock Return SyntaxKind.TryKeyword Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock Return SyntaxKind.DoKeyword Case SyntaxKind.ForBlock, SyntaxKind.ForEachBlock Return SyntaxKind.ForKeyword Case SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock Return SyntaxKind.SelectKeyword Case SyntaxKind.SubBlock Return SyntaxKind.SubKeyword Case SyntaxKind.FunctionBlock Return SyntaxKind.FunctionKeyword Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock Return SyntaxKind.PropertyKeyword Case Else Return Nothing End Select End Function Private Shared Function BlockKindToStatementKind(blockKind As SyntaxKind) As SyntaxKind Select Case blockKind Case SyntaxKind.WhileBlock Return SyntaxKind.ExitWhileStatement Case SyntaxKind.TryBlock, SyntaxKind.CatchBlock Return SyntaxKind.ExitTryStatement Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock Return SyntaxKind.ExitDoStatement Case SyntaxKind.ForBlock, SyntaxKind.ForEachBlock Return SyntaxKind.ExitForStatement Case SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock Return SyntaxKind.ExitSelectStatement Case SyntaxKind.SubBlock Return SyntaxKind.ExitSubStatement Case SyntaxKind.FunctionBlock Return SyntaxKind.ExitFunctionStatement Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock Return SyntaxKind.ExitPropertyStatement Case Else Throw ExceptionUtilities.UnexpectedValue(blockKind) End Select End Function Private Shared Function BlockKindToContinuableStatementKind(blockKind As SyntaxKind) As SyntaxKind Select Case blockKind Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock Return SyntaxKind.ContinueDoStatement Case SyntaxKind.ForBlock, SyntaxKind.ForEachBlock Return SyntaxKind.ContinueForStatement Case SyntaxKind.WhileBlock Return SyntaxKind.ContinueWhileStatement Case Else Throw ExceptionUtilities.UnexpectedValue(blockKind) End Select End Function Private Shared Sub CreateAddKeywordActions(node As SyntaxNode, document As Document, enclosingBlock As SyntaxNode, blockKinds As IEnumerable(Of SyntaxKind), updateNode As Func(Of SyntaxNode, SyntaxNode, SyntaxKind, Document, CancellationToken, StatementSyntax), codeActions As IList(Of CodeAction)) codeActions.AddRange(blockKinds.Select(Function(bk) New AddKeywordCodeAction(node, bk, enclosingBlock, document, updateNode))) End Sub Private Shared Sub CreateReplaceKeywordActions(blockKinds As IEnumerable(Of SyntaxKind), invalidToken As SyntaxToken, node As SyntaxNode, enclosingBlock As SyntaxNode, document As Document, updateNode As Func(Of SyntaxNode, SyntaxNode, SyntaxKind, Document, CancellationToken, StatementSyntax), codeActions As IList(Of CodeAction)) codeActions.AddRange(blockKinds.Select(Function(bk) New ReplaceKeywordCodeAction(bk, invalidToken, node, enclosingBlock, document, updateNode))) End Sub Private Shared Sub CreateReplaceTokenKeywordActions(blockKinds As IEnumerable(Of SyntaxKind), invalidToken As SyntaxToken, document As Document, codeActions As List(Of CodeAction)) codeActions.AddRange(blockKinds.Select(Function(bk) New ReplaceTokenKeywordCodeAction(bk, invalidToken, document))) End Sub Private Shared Function CreateDeleteString(node As SyntaxNode) As String Return String.Format(VBFeaturesResources.Delete_the_0_statement1, node.ToString().Trim()) End Function End Class End Namespace
-1
dotnet/roslyn
55,054
Map documents to be reanalyzed back from compile-time to design-time documents
Fixes https://github.com/dotnet/roslyn/issues/54582
tmat
2021-07-22T20:16:13Z
2021-07-22T23:14:58Z
fae6a8fa7955ef8345c03a53f761e78c981ddd6e
28b9b16c41c82988955bf954915a9369546075f5
Map documents to be reanalyzed back from compile-time to design-time documents. Fixes https://github.com/dotnet/roslyn/issues/54582
./src/Features/LanguageServer/Protocol/Handler/Commands/AbstractExecuteWorkspaceCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Commands { internal abstract class AbstractExecuteWorkspaceCommandHandler : IRequestHandler<ExecuteCommandParams, object> { public string Method => GetRequestNameForCommandName(Command); public abstract string Command { get; } public abstract bool MutatesSolutionState { get; } public abstract bool RequiresLSPSolution { get; } public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(ExecuteCommandParams request); public abstract Task<object> HandleRequestAsync(ExecuteCommandParams request, RequestContext context, CancellationToken cancellationToken); public static string GetRequestNameForCommandName(string commandName) => $"{Methods.WorkspaceExecuteCommandName}/{commandName}"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Commands { internal abstract class AbstractExecuteWorkspaceCommandHandler : IRequestHandler<ExecuteCommandParams, object> { public string Method => GetRequestNameForCommandName(Command); public abstract string Command { get; } public abstract bool MutatesSolutionState { get; } public abstract bool RequiresLSPSolution { get; } public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(ExecuteCommandParams request); public abstract Task<object> HandleRequestAsync(ExecuteCommandParams request, RequestContext context, CancellationToken cancellationToken); public static string GetRequestNameForCommandName(string commandName) => $"{Methods.WorkspaceExecuteCommandName}/{commandName}"; } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class GeneratorDriverTests : CSharpTestBase { [Fact] public void Running_With_No_Changes_Is_NoOp() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Empty(diagnostics); Assert.Single(outputCompilation.SyntaxTrees); Assert.Equal(compilation, outputCompilation); } [Fact] public void Generator_Is_Initialized_Before_Running() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(1, initCount); Assert.Equal(1, executeCount); } [Fact] public void Generator_Is_Not_Initialized_If_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); Assert.Equal(0, initCount); Assert.Equal(0, executeCount); } [Fact] public void Generator_Is_Only_Initialized_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); Assert.Equal(1, initCount); Assert.Equal(3, executeCount); } [Fact] public void Single_File_Is_Added() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation); var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single(); Assert.True(generatedClass.Locations.Single().IsInSource); } [Fact] public void Analyzer_Is_Run() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; var analyzer = new Analyzer_Is_Run_Analyzer(); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.GeneratedClassCount); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.GeneratedClassCount); } private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer { public int GeneratedClassCount; 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.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "GeneratedClass": Interlocked.Increment(ref GeneratedClassCount); break; case "C": case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _); Assert.Equal(2, outputCompilation1.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation2.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation3.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation1); Assert.NotEqual(compilation, outputCompilation2); Assert.NotEqual(compilation, outputCompilation3); } [Fact] public void User_Source_Can_Depend_On_Generated_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); } [Fact] public void Error_During_Initialization_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_Generator_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Single(outputCompilation.SyntaxTrees); } [Fact] public void Error_During_Generation_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Does_Not_Affect_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_With_Dependent_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Has_Exception_In_Description() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); // Since translated description strings can have punctuation that differs based on locale, simply ensure the // exception message is contains in the diagnostic description. Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString()); } [Fact] public void Generator_Can_Report_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( Diagnostic("TG001").WithLocation(1, 1) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54185: the addition happens later so the exceptions don't occur directly at add-time. we should decide if this subtle behavior change is acceptable")] public void Generator_HintName_MustBe_Unique() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); // the assert should swallow the exception, so we'll actually successfully generate Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8))); // also throws for <name> vs <name>.cs Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8))); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void Generator_HintName_Is_Appended_With_GeneratorName() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(3, outputCompilation.SyntaxTrees.Count()); var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray(); Assert.Equal(new[] { Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"), Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs") }, filePaths); } [Fact] public void RunResults_Are_Empty_Before_Generation() { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Empty(results.Diagnostics); Assert.Empty(results.Results); } [Fact] public void RunResults_Are_Available_After_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.GeneratedTrees); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results.Single(); Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Single(result.GeneratedSources); Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree); } [Fact] public void RunResults_Combine_SyntaxTrees() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); }); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void RunResults_Combine_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(2, results.Results.Length); Assert.Equal(3, results.Diagnostics.Length); Assert.Empty(results.GeneratedTrees); var result1 = results.Results[0]; var result2 = results.Results[1]; Assert.Null(result1.Exception); Assert.Equal(2, result1.Diagnostics.Length); Assert.Empty(result1.GeneratedSources); Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]); Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]); Assert.Null(result2.Exception); Assert.Single(result2.Diagnostics); Assert.Empty(result2.GeneratedSources); Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]); } [Fact] public void FullGeneration_Diagnostics_AreSame_As_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics); var results = driver.GetRunResult(); Assert.Equal(3, results.Diagnostics.Length); Assert.Equal(3, fullDiagnostics.Length); AssertEx.Equal(results.Diagnostics, fullDiagnostics); } [Fact] public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { cts.Cancel(); } ); // test generator cancels the token. Check that the call to this generator doesn't make it look like it errored. var testGenerator2 = new CallbackGenerator2( onInit: (i) => { }, onExecute: (e) => { e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8)); e.CancellationToken.ThrowIfCancellationRequested(); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); var oldDriver = driver; Assert.Throws<OperationCanceledException>(() => driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token) ); Assert.Same(oldDriver, driver); } [ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")] public void Adding_A_Source_Text_Without_Encoding_Fails_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics); Assert.Single(outputDiagnostics); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The SourceText with hintName 'a.cs' must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1) ); } [Fact] public void ParseOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ParseOptions? passedOptions = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { passedOptions = e.ParseOptions; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Same(parseOptions, passedOptions); } [Fact] public void AdditionalFiles_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var texts = ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a", "abc"), new InMemoryAdditionalText("b", "def")); ImmutableArray<AdditionalText> passedIn = default; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AdditionalFiles ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, additionalTexts: texts); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Equal(2, passedIn.Length); Assert.Equal<AdditionalText>(texts, passedIn); } [Fact] public void AnalyzerConfigOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var options = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("a", "abc").Add("b", "def"))); AnalyzerConfigOptionsProvider? passedIn = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AnalyzerConfigOptions ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, optionsProvider: options); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(passedIn); Assert.True(passedIn!.GlobalOptions.TryGetValue("a", out var item1)); Assert.Equal("abc", item1); Assert.True(passedIn!.GlobalOptions.TryGetValue("b", out var item2)); Assert.Equal("def", item2); } [Fact] public void Generator_Can_Provide_Source_In_PostInit() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void PostInit_Source_Is_Available_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Is_Only_Called_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int postInitCount = 0; int executeCount = 0; void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); postInitCount++; } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(1, postInitCount); Assert.Equal(3, executeCount); } [Fact] public void Error_During_PostInit_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); throw new InvalidOperationException("post init error"); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_PostInit_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void init(GeneratorInitializationContext context) { context.RegisterForPostInitialization(postInit); throw new InvalidOperationException("init error"); } static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); Assert.True(false, "Should not execute"); } var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void PostInit_SyntaxTrees_Are_Available_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results[0]; Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Equal(2, result.GeneratedSources.Length); } [Fact] public void PostInit_SyntaxTrees_Are_Combined_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void SyntaxTrees_Are_Lazy() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); var tree = Assert.Single(results.GeneratedTrees); Assert.False(tree.TryGetRoot(out _)); var rootFromGetRoot = tree.GetRoot(); Assert.NotNull(rootFromGetRoot); Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot)); Assert.Same(rootFromGetRoot, rootFromTryGetRoot); } [Fact] public void Diagnostics_Respect_Suppression() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2)); c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3)); }); var options = ((CSharpCompilationOptions)compilation.Options); // generator driver diagnostics are reported separately from the compilation verifyDiagnosticsWithOptions(options, Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be individually suppressed verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress), Diagnostic("GEN001").WithLocation(1, 1)); // warning level is respected verifyDiagnosticsWithOptions(options.WithWarningLevel(0)); verifyDiagnosticsWithOptions(options.WithWarningLevel(2), Diagnostic("GEN001").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithWarningLevel(3), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be upgraded to errors verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true)); void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected) { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); var updatedCompilation = compilation.WithOptions(options); driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void Diagnostics_Respect_Pragma_Suppression() { var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2); // reported diagnostics can have a location in source verifyDiagnosticsWithSource("//comment", new[] { (gen001, TextSpan.FromBounds(2, 5)) }, Diagnostic("GEN001", "com").WithLocation(1, 3)); // diagnostics are suppressed via #pragma verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, TextSpan.FromBounds(27, 30)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // but not when they don't have a source location verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, new TextSpan(0, 0)) }, Diagnostic("GEN001").WithLocation(1, 1)); // can be suppressed explicitly verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment", new[] { (gen001, TextSpan.FromBounds(34, 37)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // suppress + restore verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment #pragma warning restore GEN001 //another", new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3), Diagnostic("GEN001", "ano").WithLocation(4, 3)); void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected) { var parseOptions = TestOptions.Regular; source = source.Replace(Environment.NewLine, "\r\n"); Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { foreach ((var d, var l) in reportDiagnostics) { if (l.IsEmpty) { c.ReportDiagnostic(d); } else { c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l))); } } }); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void GeneratorDriver_Prefers_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); int incrementalInitCount = 0; var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); int dualInitCount = 0, dualExecuteCount = 0, dualIncrementalInitCount = 0; var generator3 = new IncrementalAndSourceCallbackGenerator((ic) => dualInitCount++, (sgc) => dualExecuteCount++, (ic) => dualIncrementalInitCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran individual incremental and source generators Assert.Equal(1, initCount); Assert.Equal(1, executeCount); Assert.Equal(1, incrementalInitCount); // ran the combined generator only as an IIncrementalGenerator Assert.Equal(0, dualInitCount); Assert.Equal(0, dualExecuteCount); Assert.Equal(1, dualIncrementalInitCount); } [Fact] public void GeneratorDriver_Initializes_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int incrementalInitCount = 0; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran the incremental generator Assert.Equal(1, incrementalInitCount); } [Fact] public void Incremental_Generators_Exception_During_Initialization() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => throw e)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Stop_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Equal(2, runResults.Results.Length); Assert.Single(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void IncrementalGenerator_With_No_Pipeline_Callback_Is_Valid() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => { })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); Assert.Empty(diagnostics); } [Fact] public void IncrementalGenerator_Can_Add_PostInit_Source() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => ic.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.Empty(diagnostics); } [Fact] public void User_WrappedFunc_Throw_Exceptions() { Func<int, CancellationToken, int> func = (input, _) => input; Func<int, CancellationToken, int> throwsFunc = (input, _) => throw new InvalidOperationException("user code exception"); Func<int, CancellationToken, int> timeoutFunc = (input, ct) => { ct.ThrowIfCancellationRequested(); return input; }; Func<int, CancellationToken, int> otherTimeoutFunc = (input, _) => throw new OperationCanceledException(); var userFunc = func.WrapUserFunction(); var userThrowsFunc = throwsFunc.WrapUserFunction(); var userTimeoutFunc = timeoutFunc.WrapUserFunction(); var userOtherTimeoutFunc = otherTimeoutFunc.WrapUserFunction(); // user functions return same values when wrapped var result = userFunc(10, CancellationToken.None); var userResult = userFunc(10, CancellationToken.None); Assert.Equal(10, result); Assert.Equal(result, userResult); // exceptions thrown in user code are wrapped Assert.Throws<InvalidOperationException>(() => throwsFunc(20, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userThrowsFunc(20, CancellationToken.None)); try { userThrowsFunc(20, CancellationToken.None); } catch (UserFunctionException e) { Assert.IsType<InvalidOperationException>(e.InnerException); } // cancellation is not wrapped, and is bubbled up Assert.Throws<OperationCanceledException>(() => timeoutFunc(30, new CancellationToken(true))); Assert.Throws<OperationCanceledException>(() => userTimeoutFunc(30, new CancellationToken(true))); // unless it wasn't *our* cancellation token, in which case it still gets wrapped Assert.Throws<OperationCanceledException>(() => otherTimeoutFunc(30, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userOtherTimeoutFunc(30, CancellationToken.None)); } [Fact] public void IncrementalGenerator_Doesnt_Run_For_Same_Input() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var filePaths = ctx.CompilationProvider.SelectMany((c, _) => c.SyntaxTrees).Select((tree, _) => tree.FilePath); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // run the same compilation through again, and confirm the output wasn't called driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Runs_Only_For_Changed_Inputs() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var text1 = new InMemoryAdditionalText("Text1", "content1"); var text2 = new InMemoryAdditionalText("Text2", "content2"); List<Compilation> compilationsCalledFor = new List<Compilation>(); List<AdditionalText> textsCalledFor = new List<AdditionalText>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, c) => { textsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, additionalTexts: new[] { text1 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text1, textsCalledFor[0]); // clear the results, add an additional text, but keep the compilation the same compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.AddAdditionalTexts(ImmutableArray.Create<AdditionalText>(text2)); driver = driver.RunGenerators(compilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text2, textsCalledFor[0]); // now edit the compilation compilationsCalledFor.Clear(); textsCalledFor.Clear(); var newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newComp")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(newCompilation, compilationsCalledFor[0]); Assert.Equal(0, textsCalledFor.Count); // re run without changing anything compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.RunGenerators(newCompilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(0, textsCalledFor.Count); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Input_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.WithComparer(new LambdaComparer<Compilation>((c1, c2) => true, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // now edit the compilation, run the generator, and confirm that the output was not called again this time Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Combine_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<AdditionalText> texts = new List<AdditionalText>() { new InMemoryAdditionalText("abc", "") }; List<(Compilation, ImmutableArray<AdditionalText>)> calledFor = new List<(Compilation, ImmutableArray<AdditionalText>)>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.Combine(ctx.AdditionalTextsProvider.Collect()) // comparer that ignores the LHS (additional texts) .WithComparer(new LambdaComparer<(Compilation, ImmutableArray<AdditionalText>)>((c1, c2) => c1.Item1 == c2.Item1, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { calledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation + additional texts GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: texts); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); Assert.Equal(compilation, calledFor[0].Item1); Assert.Equal(texts[0], calledFor[0].Item2.Single()); // edit the additional texts, and verify that the output was *not* called again on the next run driver = driver.RemoveAdditionalTexts(texts.ToImmutableArray()); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); // now edit the compilation, run the generator, and confirm that the output *was* called again this time with the new compilation and no additional texts Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(2, calledFor.Count); Assert.Equal(newCompilation, calledFor[1].Item1); Assert.Empty(calledFor[1].Item2); } [Fact] public void IncrementalGenerator_Register_End_Node_Only_Once_Through_Combines() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var source = ctx.CompilationProvider; var source2 = ctx.CompilationProvider.Combine(source); var source3 = ctx.CompilationProvider.Combine(source2); var source4 = ctx.CompilationProvider.Combine(source3); var source5 = ctx.CompilationProvider.Combine(source4); ctx.RegisterSourceOutput(source5, (spc, c) => { compilationsCalledFor.Add(c.Item1); }); })); // run the generator and check that we didn't multiple register the generate source node through the combine GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_PostInit_Source_Is_Cached() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ClassDeclarationSyntax> classes = new List<ClassDeclarationSyntax>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")); ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is ClassDeclarationSyntax, (gsc, _) => (ClassDeclarationSyntax)gsc.Node), (spc, node) => classes.Add(node)); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(2, classes.Count); Assert.Equal("C", classes[0].Identifier.ValueText); Assert.Equal("D", classes[1].Identifier.ValueText); // clear classes, re-run classes.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(classes); // modify the original tree, see that the post init is still cached var c2 = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText("class E{}", parseOptions)); classes.Clear(); driver = driver.RunGenerators(c2); Assert.Single(classes); Assert.Equal("E", classes[0].Identifier.ValueText); } [Fact] public void Incremental_Generators_Can_Be_Cancelled() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); bool generatorCancelled = false; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { var step1 = ctx.CompilationProvider.Select((c, ct) => { generatorCancelled = true; cts.Cancel(); return c; }); var step2 = step1.Select((c, ct) => { ct.ThrowIfCancellationRequested(); return c; }); ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("a", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token)); Assert.True(generatorCancelled); } [Fact] public void ParseOptions_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ParseOptions> parseOptionsCalledFor = new List<ParseOptions>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, p) => { parseOptionsCalledFor.Add(p); }); })); // run the generator once, and check it was passed the parse options GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(parseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // now update the parse options parseOptionsCalledFor.Clear(); var newParseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose); driver = driver.WithUpdatedParseOptions(newParseOptions); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(newParseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedParseOptions(null!)); } [Fact] public void AnalyzerConfig_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string? analyzerOptionsValue = string.Empty; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, p) => p.GlobalOptions.TryGetValue("test", out analyzerOptionsValue)); })); var builder = ImmutableDictionary<string, string>.Empty.ToBuilder(); builder.Add("test", "value1"); var optionsProvider = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(builder.ToImmutable())); // run the generator once, and check it was passed the configs GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, optionsProvider: optionsProvider); driver = driver.RunGenerators(compilation); Assert.Equal("value1", analyzerOptionsValue); // clear the results, and re-run analyzerOptionsValue = null; driver = driver.RunGenerators(compilation); Assert.Null(analyzerOptionsValue); // now update the config analyzerOptionsValue = null; builder.Clear(); builder.Add("test", "value2"); var newOptionsProvider = optionsProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(builder.ToImmutable())); driver = driver.WithUpdatedAnalyzerConfigOptions(newOptionsProvider); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal("value2", analyzerOptionsValue); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedAnalyzerConfigOptions(null!)); } [Fact] public void AdditionalText_Can_Be_Replaced() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText1 = new InMemoryAdditionalText("path1.txt", ""); InMemoryAdditionalText additionalText2 = new InMemoryAdditionalText("path2.txt", ""); InMemoryAdditionalText additionalText3 = new InMemoryAdditionalText("path3.txt", ""); List<string?> additionalTextPaths = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider.Select((t, _) => t.Path), (spc, p) => { additionalTextPaths.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText1, additionalText2, additionalText3 }); driver = driver.RunGenerators(compilation); Assert.Equal(3, additionalTextPaths.Count); Assert.Equal("path1.txt", additionalTextPaths[0]); Assert.Equal("path2.txt", additionalTextPaths[1]); Assert.Equal("path3.txt", additionalTextPaths[2]); // re-run and check nothing else got added additionalTextPaths.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); driver = driver.ReplaceAdditionalText(additionalText2, new InMemoryAdditionalText("path4.txt", "")); // run, and check that only the replaced file was invoked driver = driver.RunGenerators(compilation); Assert.Single(additionalTextPaths); Assert.Equal("path4.txt", additionalTextPaths[0]); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.ReplaceAdditionalText(additionalText1, null!)); } [Fact] public void Replaced_Input_Is_Treated_As_Modified() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText = new InMemoryAdditionalText("path.txt", "abc"); List<string?> additionalTextPaths = new List<string?>(); List<string?> additionalTextsContents = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var texts = ctx.AdditionalTextsProvider; var paths = texts.Select((t, _) => t?.Path); var contents = texts.Select((t, _) => t?.GetText()?.ToString()); ctx.RegisterSourceOutput(paths, (spc, p) => { additionalTextPaths.Add(p); }); ctx.RegisterSourceOutput(contents, (spc, p) => { additionalTextsContents.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText }); driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path.txt", additionalTextPaths[0]); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("abc", additionalTextsContents[0]); // re-run and check nothing else got added driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal(1, additionalTextsContents.Count); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); additionalTextsContents.Clear(); var secondText = new InMemoryAdditionalText("path.txt", "def"); driver = driver.ReplaceAdditionalText(additionalText, secondText); // run, and check that only the contents got re-run driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("def", additionalTextsContents[0]); // now replace the text with a different path, but the same text additionalTextPaths.Clear(); additionalTextsContents.Clear(); var thirdText = new InMemoryAdditionalText("path2.txt", "def"); driver = driver.ReplaceAdditionalText(secondText, thirdText); // run, and check that only the paths got re-run driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path2.txt", additionalTextPaths[0]); Assert.Empty(additionalTextsContents); } [Theory] [CombinatorialData] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] public void Generator_Output_Kinds_Can_Be_Disabled(IncrementalGeneratorOutputKind disabledOutput) { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new PipelineCallbackGenerator(ctx => { ctx.RegisterPostInitializationOutput((context) => context.AddSource("PostInit", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Source", "")); ctx.RegisterImplementationSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Implementation", "")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, driverOptions: new GeneratorDriverOptions(disabledOutput), parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var result = driver.GetRunResult(); Assert.Single(result.Results); Assert.Empty(result.Results[0].Diagnostics); // verify the expected outputs were generated // NOTE: adding new output types will cause this test to fail. Update above as needed. foreach (IncrementalGeneratorOutputKind kind in Enum.GetValues(typeof(IncrementalGeneratorOutputKind))) { if (kind == IncrementalGeneratorOutputKind.None) continue; if (disabledOutput.HasFlag((IncrementalGeneratorOutputKind)kind)) { Assert.DoesNotContain(result.Results[0].GeneratedSources, isTextForKind); } else { Assert.Contains(result.Results[0].GeneratedSources, isTextForKind); } bool isTextForKind(GeneratedSourceResult s) => s.HintName == Enum.GetName(typeof(IncrementalGeneratorOutputKind), kind) + ".cs"; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class GeneratorDriverTests : CSharpTestBase { [Fact] public void Running_With_No_Changes_Is_NoOp() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Empty(diagnostics); Assert.Single(outputCompilation.SyntaxTrees); Assert.Equal(compilation, outputCompilation); } [Fact] public void Generator_Is_Initialized_Before_Running() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(1, initCount); Assert.Equal(1, executeCount); } [Fact] public void Generator_Is_Not_Initialized_If_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); Assert.Equal(0, initCount); Assert.Equal(0, executeCount); } [Fact] public void Generator_Is_Only_Initialized_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); Assert.Equal(1, initCount); Assert.Equal(3, executeCount); } [Fact] public void Single_File_Is_Added() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation); var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single(); Assert.True(generatedClass.Locations.Single().IsInSource); } [Fact] public void Analyzer_Is_Run() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; var analyzer = new Analyzer_Is_Run_Analyzer(); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.GeneratedClassCount); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.GeneratedClassCount); } private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer { public int GeneratedClassCount; 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.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "GeneratedClass": Interlocked.Increment(ref GeneratedClassCount); break; case "C": case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _); Assert.Equal(2, outputCompilation1.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation2.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation3.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation1); Assert.NotEqual(compilation, outputCompilation2); Assert.NotEqual(compilation, outputCompilation3); } [Fact] public void User_Source_Can_Depend_On_Generated_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); } [Fact] public void Error_During_Initialization_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_Generator_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Single(outputCompilation.SyntaxTrees); } [Fact] public void Error_During_Generation_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Does_Not_Affect_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_With_Dependent_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Has_Exception_In_Description() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); // Since translated description strings can have punctuation that differs based on locale, simply ensure the // exception message is contains in the diagnostic description. Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString()); } [Fact] public void Generator_Can_Report_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( Diagnostic("TG001").WithLocation(1, 1) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54185: the addition happens later so the exceptions don't occur directly at add-time. we should decide if this subtle behavior change is acceptable")] public void Generator_HintName_MustBe_Unique() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); // the assert should swallow the exception, so we'll actually successfully generate Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8))); // also throws for <name> vs <name>.cs Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8))); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void Generator_HintName_Is_Appended_With_GeneratorName() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(3, outputCompilation.SyntaxTrees.Count()); var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray(); Assert.Equal(new[] { Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"), Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs") }, filePaths); } [Fact] public void RunResults_Are_Empty_Before_Generation() { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Empty(results.Diagnostics); Assert.Empty(results.Results); } [Fact] public void RunResults_Are_Available_After_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.GeneratedTrees); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results.Single(); Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Single(result.GeneratedSources); Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree); } [Fact] public void RunResults_Combine_SyntaxTrees() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); }); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void RunResults_Combine_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(2, results.Results.Length); Assert.Equal(3, results.Diagnostics.Length); Assert.Empty(results.GeneratedTrees); var result1 = results.Results[0]; var result2 = results.Results[1]; Assert.Null(result1.Exception); Assert.Equal(2, result1.Diagnostics.Length); Assert.Empty(result1.GeneratedSources); Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]); Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]); Assert.Null(result2.Exception); Assert.Single(result2.Diagnostics); Assert.Empty(result2.GeneratedSources); Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]); } [Fact] public void FullGeneration_Diagnostics_AreSame_As_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics); var results = driver.GetRunResult(); Assert.Equal(3, results.Diagnostics.Length); Assert.Equal(3, fullDiagnostics.Length); AssertEx.Equal(results.Diagnostics, fullDiagnostics); } [Fact] public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { cts.Cancel(); } ); // test generator cancels the token. Check that the call to this generator doesn't make it look like it errored. var testGenerator2 = new CallbackGenerator2( onInit: (i) => { }, onExecute: (e) => { e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8)); e.CancellationToken.ThrowIfCancellationRequested(); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); var oldDriver = driver; Assert.Throws<OperationCanceledException>(() => driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token) ); Assert.Same(oldDriver, driver); } [ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")] public void Adding_A_Source_Text_Without_Encoding_Fails_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics); Assert.Single(outputDiagnostics); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The SourceText with hintName 'a.cs' must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1) ); } [Fact] public void ParseOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ParseOptions? passedOptions = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { passedOptions = e.ParseOptions; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Same(parseOptions, passedOptions); } [Fact] public void AdditionalFiles_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var texts = ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a", "abc"), new InMemoryAdditionalText("b", "def")); ImmutableArray<AdditionalText> passedIn = default; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AdditionalFiles ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, additionalTexts: texts); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Equal(2, passedIn.Length); Assert.Equal<AdditionalText>(texts, passedIn); } [Fact] public void AnalyzerConfigOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var options = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("a", "abc").Add("b", "def"))); AnalyzerConfigOptionsProvider? passedIn = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AnalyzerConfigOptions ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, optionsProvider: options); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(passedIn); Assert.True(passedIn!.GlobalOptions.TryGetValue("a", out var item1)); Assert.Equal("abc", item1); Assert.True(passedIn!.GlobalOptions.TryGetValue("b", out var item2)); Assert.Equal("def", item2); } [Fact] public void Generator_Can_Provide_Source_In_PostInit() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void PostInit_Source_Is_Available_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Is_Only_Called_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int postInitCount = 0; int executeCount = 0; void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); postInitCount++; } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(1, postInitCount); Assert.Equal(3, executeCount); } [Fact] public void Error_During_PostInit_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); throw new InvalidOperationException("post init error"); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_PostInit_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void init(GeneratorInitializationContext context) { context.RegisterForPostInitialization(postInit); throw new InvalidOperationException("init error"); } static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); Assert.True(false, "Should not execute"); } var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void PostInit_SyntaxTrees_Are_Available_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results[0]; Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Equal(2, result.GeneratedSources.Length); } [Fact] public void PostInit_SyntaxTrees_Are_Combined_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void SyntaxTrees_Are_Lazy() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); var tree = Assert.Single(results.GeneratedTrees); Assert.False(tree.TryGetRoot(out _)); var rootFromGetRoot = tree.GetRoot(); Assert.NotNull(rootFromGetRoot); Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot)); Assert.Same(rootFromGetRoot, rootFromTryGetRoot); } [Fact] public void Diagnostics_Respect_Suppression() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2)); c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3)); }); var options = ((CSharpCompilationOptions)compilation.Options); // generator driver diagnostics are reported separately from the compilation verifyDiagnosticsWithOptions(options, Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be individually suppressed verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress), Diagnostic("GEN001").WithLocation(1, 1)); // warning level is respected verifyDiagnosticsWithOptions(options.WithWarningLevel(0)); verifyDiagnosticsWithOptions(options.WithWarningLevel(2), Diagnostic("GEN001").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithWarningLevel(3), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be upgraded to errors verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true)); void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected) { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); var updatedCompilation = compilation.WithOptions(options); driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void Diagnostics_Respect_Pragma_Suppression() { var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2); // reported diagnostics can have a location in source verifyDiagnosticsWithSource("//comment", new[] { (gen001, TextSpan.FromBounds(2, 5)) }, Diagnostic("GEN001", "com").WithLocation(1, 3)); // diagnostics are suppressed via #pragma verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, TextSpan.FromBounds(27, 30)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // but not when they don't have a source location verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, new TextSpan(0, 0)) }, Diagnostic("GEN001").WithLocation(1, 1)); // can be suppressed explicitly verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment", new[] { (gen001, TextSpan.FromBounds(34, 37)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // suppress + restore verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment #pragma warning restore GEN001 //another", new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3), Diagnostic("GEN001", "ano").WithLocation(4, 3)); void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected) { var parseOptions = TestOptions.Regular; source = source.Replace(Environment.NewLine, "\r\n"); Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { foreach ((var d, var l) in reportDiagnostics) { if (l.IsEmpty) { c.ReportDiagnostic(d); } else { c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l))); } } }); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void GeneratorDriver_Prefers_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); int incrementalInitCount = 0; var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); int dualInitCount = 0, dualExecuteCount = 0, dualIncrementalInitCount = 0; var generator3 = new IncrementalAndSourceCallbackGenerator((ic) => dualInitCount++, (sgc) => dualExecuteCount++, (ic) => dualIncrementalInitCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran individual incremental and source generators Assert.Equal(1, initCount); Assert.Equal(1, executeCount); Assert.Equal(1, incrementalInitCount); // ran the combined generator only as an IIncrementalGenerator Assert.Equal(0, dualInitCount); Assert.Equal(0, dualExecuteCount); Assert.Equal(1, dualIncrementalInitCount); } [Fact] public void GeneratorDriver_Initializes_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int incrementalInitCount = 0; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran the incremental generator Assert.Equal(1, incrementalInitCount); } [Fact] public void Incremental_Generators_Exception_During_Initialization() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => throw e)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Stop_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Equal(2, runResults.Results.Length); Assert.Single(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void IncrementalGenerator_With_No_Pipeline_Callback_Is_Valid() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => { })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); Assert.Empty(diagnostics); } [Fact] public void IncrementalGenerator_Can_Add_PostInit_Source() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => ic.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.Empty(diagnostics); } [Fact] public void User_WrappedFunc_Throw_Exceptions() { Func<int, CancellationToken, int> func = (input, _) => input; Func<int, CancellationToken, int> throwsFunc = (input, _) => throw new InvalidOperationException("user code exception"); Func<int, CancellationToken, int> timeoutFunc = (input, ct) => { ct.ThrowIfCancellationRequested(); return input; }; Func<int, CancellationToken, int> otherTimeoutFunc = (input, _) => throw new OperationCanceledException(); var userFunc = func.WrapUserFunction(); var userThrowsFunc = throwsFunc.WrapUserFunction(); var userTimeoutFunc = timeoutFunc.WrapUserFunction(); var userOtherTimeoutFunc = otherTimeoutFunc.WrapUserFunction(); // user functions return same values when wrapped var result = userFunc(10, CancellationToken.None); var userResult = userFunc(10, CancellationToken.None); Assert.Equal(10, result); Assert.Equal(result, userResult); // exceptions thrown in user code are wrapped Assert.Throws<InvalidOperationException>(() => throwsFunc(20, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userThrowsFunc(20, CancellationToken.None)); try { userThrowsFunc(20, CancellationToken.None); } catch (UserFunctionException e) { Assert.IsType<InvalidOperationException>(e.InnerException); } // cancellation is not wrapped, and is bubbled up Assert.Throws<OperationCanceledException>(() => timeoutFunc(30, new CancellationToken(true))); Assert.Throws<OperationCanceledException>(() => userTimeoutFunc(30, new CancellationToken(true))); // unless it wasn't *our* cancellation token, in which case it still gets wrapped Assert.Throws<OperationCanceledException>(() => otherTimeoutFunc(30, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userOtherTimeoutFunc(30, CancellationToken.None)); } [Fact] public void IncrementalGenerator_Doesnt_Run_For_Same_Input() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var filePaths = ctx.CompilationProvider.SelectMany((c, _) => c.SyntaxTrees).Select((tree, _) => tree.FilePath); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // run the same compilation through again, and confirm the output wasn't called driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Runs_Only_For_Changed_Inputs() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var text1 = new InMemoryAdditionalText("Text1", "content1"); var text2 = new InMemoryAdditionalText("Text2", "content2"); List<Compilation> compilationsCalledFor = new List<Compilation>(); List<AdditionalText> textsCalledFor = new List<AdditionalText>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, c) => { textsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, additionalTexts: new[] { text1 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text1, textsCalledFor[0]); // clear the results, add an additional text, but keep the compilation the same compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.AddAdditionalTexts(ImmutableArray.Create<AdditionalText>(text2)); driver = driver.RunGenerators(compilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text2, textsCalledFor[0]); // now edit the compilation compilationsCalledFor.Clear(); textsCalledFor.Clear(); var newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newComp")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(newCompilation, compilationsCalledFor[0]); Assert.Equal(0, textsCalledFor.Count); // re run without changing anything compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.RunGenerators(newCompilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(0, textsCalledFor.Count); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Input_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.WithComparer(new LambdaComparer<Compilation>((c1, c2) => true, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // now edit the compilation, run the generator, and confirm that the output was not called again this time Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Combine_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<AdditionalText> texts = new List<AdditionalText>() { new InMemoryAdditionalText("abc", "") }; List<(Compilation, ImmutableArray<AdditionalText>)> calledFor = new List<(Compilation, ImmutableArray<AdditionalText>)>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.Combine(ctx.AdditionalTextsProvider.Collect()) // comparer that ignores the LHS (additional texts) .WithComparer(new LambdaComparer<(Compilation, ImmutableArray<AdditionalText>)>((c1, c2) => c1.Item1 == c2.Item1, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { calledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation + additional texts GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: texts); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); Assert.Equal(compilation, calledFor[0].Item1); Assert.Equal(texts[0], calledFor[0].Item2.Single()); // edit the additional texts, and verify that the output was *not* called again on the next run driver = driver.RemoveAdditionalTexts(texts.ToImmutableArray()); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); // now edit the compilation, run the generator, and confirm that the output *was* called again this time with the new compilation and no additional texts Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(2, calledFor.Count); Assert.Equal(newCompilation, calledFor[1].Item1); Assert.Empty(calledFor[1].Item2); } [Fact] public void IncrementalGenerator_Register_End_Node_Only_Once_Through_Combines() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var source = ctx.CompilationProvider; var source2 = ctx.CompilationProvider.Combine(source); var source3 = ctx.CompilationProvider.Combine(source2); var source4 = ctx.CompilationProvider.Combine(source3); var source5 = ctx.CompilationProvider.Combine(source4); ctx.RegisterSourceOutput(source5, (spc, c) => { compilationsCalledFor.Add(c.Item1); }); })); // run the generator and check that we didn't multiple register the generate source node through the combine GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_PostInit_Source_Is_Cached() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ClassDeclarationSyntax> classes = new List<ClassDeclarationSyntax>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")); ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is ClassDeclarationSyntax, (gsc, _) => (ClassDeclarationSyntax)gsc.Node), (spc, node) => classes.Add(node)); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(2, classes.Count); Assert.Equal("C", classes[0].Identifier.ValueText); Assert.Equal("D", classes[1].Identifier.ValueText); // clear classes, re-run classes.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(classes); // modify the original tree, see that the post init is still cached var c2 = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText("class E{}", parseOptions)); classes.Clear(); driver = driver.RunGenerators(c2); Assert.Single(classes); Assert.Equal("E", classes[0].Identifier.ValueText); } [Fact] public void Incremental_Generators_Can_Be_Cancelled() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); bool generatorCancelled = false; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { var step1 = ctx.CompilationProvider.Select((c, ct) => { generatorCancelled = true; cts.Cancel(); return c; }); var step2 = step1.Select((c, ct) => { ct.ThrowIfCancellationRequested(); return c; }); ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("a", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token)); Assert.True(generatorCancelled); } [Fact] public void ParseOptions_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ParseOptions> parseOptionsCalledFor = new List<ParseOptions>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, p) => { parseOptionsCalledFor.Add(p); }); })); // run the generator once, and check it was passed the parse options GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(parseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // now update the parse options parseOptionsCalledFor.Clear(); var newParseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose); driver = driver.WithUpdatedParseOptions(newParseOptions); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(newParseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedParseOptions(null!)); } [Fact] public void AnalyzerConfig_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string? analyzerOptionsValue = string.Empty; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, p) => p.GlobalOptions.TryGetValue("test", out analyzerOptionsValue)); })); var builder = ImmutableDictionary<string, string>.Empty.ToBuilder(); builder.Add("test", "value1"); var optionsProvider = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(builder.ToImmutable())); // run the generator once, and check it was passed the configs GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, optionsProvider: optionsProvider); driver = driver.RunGenerators(compilation); Assert.Equal("value1", analyzerOptionsValue); // clear the results, and re-run analyzerOptionsValue = null; driver = driver.RunGenerators(compilation); Assert.Null(analyzerOptionsValue); // now update the config analyzerOptionsValue = null; builder.Clear(); builder.Add("test", "value2"); var newOptionsProvider = optionsProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(builder.ToImmutable())); driver = driver.WithUpdatedAnalyzerConfigOptions(newOptionsProvider); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal("value2", analyzerOptionsValue); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedAnalyzerConfigOptions(null!)); } [Fact] public void AdditionalText_Can_Be_Replaced() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText1 = new InMemoryAdditionalText("path1.txt", ""); InMemoryAdditionalText additionalText2 = new InMemoryAdditionalText("path2.txt", ""); InMemoryAdditionalText additionalText3 = new InMemoryAdditionalText("path3.txt", ""); List<string?> additionalTextPaths = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider.Select((t, _) => t.Path), (spc, p) => { additionalTextPaths.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText1, additionalText2, additionalText3 }); driver = driver.RunGenerators(compilation); Assert.Equal(3, additionalTextPaths.Count); Assert.Equal("path1.txt", additionalTextPaths[0]); Assert.Equal("path2.txt", additionalTextPaths[1]); Assert.Equal("path3.txt", additionalTextPaths[2]); // re-run and check nothing else got added additionalTextPaths.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); driver = driver.ReplaceAdditionalText(additionalText2, new InMemoryAdditionalText("path4.txt", "")); // run, and check that only the replaced file was invoked driver = driver.RunGenerators(compilation); Assert.Single(additionalTextPaths); Assert.Equal("path4.txt", additionalTextPaths[0]); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.ReplaceAdditionalText(additionalText1, null!)); } [Fact] public void Replaced_Input_Is_Treated_As_Modified() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText = new InMemoryAdditionalText("path.txt", "abc"); List<string?> additionalTextPaths = new List<string?>(); List<string?> additionalTextsContents = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var texts = ctx.AdditionalTextsProvider; var paths = texts.Select((t, _) => t?.Path); var contents = texts.Select((t, _) => t?.GetText()?.ToString()); ctx.RegisterSourceOutput(paths, (spc, p) => { additionalTextPaths.Add(p); }); ctx.RegisterSourceOutput(contents, (spc, p) => { additionalTextsContents.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText }); driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path.txt", additionalTextPaths[0]); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("abc", additionalTextsContents[0]); // re-run and check nothing else got added driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal(1, additionalTextsContents.Count); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); additionalTextsContents.Clear(); var secondText = new InMemoryAdditionalText("path.txt", "def"); driver = driver.ReplaceAdditionalText(additionalText, secondText); // run, and check that only the contents got re-run driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("def", additionalTextsContents[0]); // now replace the text with a different path, but the same text additionalTextPaths.Clear(); additionalTextsContents.Clear(); var thirdText = new InMemoryAdditionalText("path2.txt", "def"); driver = driver.ReplaceAdditionalText(secondText, thirdText); // run, and check that only the paths got re-run driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path2.txt", additionalTextPaths[0]); Assert.Empty(additionalTextsContents); } [Theory] [CombinatorialData] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] public void Generator_Output_Kinds_Can_Be_Disabled(IncrementalGeneratorOutputKind disabledOutput) { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new PipelineCallbackGenerator(ctx => { ctx.RegisterPostInitializationOutput((context) => context.AddSource("PostInit", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Source", "")); ctx.RegisterImplementationSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Implementation", "")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, driverOptions: new GeneratorDriverOptions(disabledOutput), parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var result = driver.GetRunResult(); Assert.Single(result.Results); Assert.Empty(result.Results[0].Diagnostics); // verify the expected outputs were generated // NOTE: adding new output types will cause this test to fail. Update above as needed. foreach (IncrementalGeneratorOutputKind kind in Enum.GetValues(typeof(IncrementalGeneratorOutputKind))) { if (kind == IncrementalGeneratorOutputKind.None) continue; if (disabledOutput.HasFlag((IncrementalGeneratorOutputKind)kind)) { Assert.DoesNotContain(result.Results[0].GeneratedSources, isTextForKind); } else { Assert.Contains(result.Results[0].GeneratedSources, isTextForKind); } bool isTextForKind(GeneratedSourceResult s) => s.HintName == Enum.GetName(typeof(IncrementalGeneratorOutputKind), kind) + ".cs"; } } [Fact] public void Metadata_References_Provider() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; var metadataRefs = new[] { MetadataReference.CreateFromAssemblyInternal(this.GetType().Assembly), MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly) }; Compilation compilation = CreateEmptyCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions, references: metadataRefs); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<string?> referenceList = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.MetadataReferencesProvider, (spc, r) => { referenceList.Add(r.Display); }); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(referenceList[0], metadataRefs[0].Display); Assert.Equal(referenceList[1], metadataRefs[1].Display); // re-run and check we didn't see anything new referenceList.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(referenceList); // Modify the reference var modifiedRef = metadataRefs[0].WithAliases(new[] { "Alias " }); metadataRefs[0] = modifiedRef; compilation = compilation.WithReferences(metadataRefs); driver = driver.RunGenerators(compilation); Assert.Single(referenceList, modifiedRef.Display); } } }
1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/Core/Portable/PublicAPI.Unshipped.txt
*REMOVED*Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode! other) -> bool abstract Microsoft.CodeAnalysis.SyntaxTree.GetLineMappings(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.LineMapping>! const Microsoft.CodeAnalysis.WellKnownMemberNames.PrintMembersMethodName = "PrintMembers" -> string! Microsoft.CodeAnalysis.Compilation.EmitDifference(Microsoft.CodeAnalysis.Emit.EmitBaseline! baseline, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Emit.SemanticEdit>! edits, System.Func<Microsoft.CodeAnalysis.ISymbol!, bool>! isAddedSymbol, System.IO.Stream! metadataStream, System.IO.Stream! ilStream, System.IO.Stream! pdbStream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult! Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.ChangedTypes.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.TypeDefinitionHandle> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedMethods.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.MethodDefinitionHandle> Microsoft.CodeAnalysis.Emit.SemanticEditKind.Replace = 4 -> Microsoft.CodeAnalysis.Emit.SemanticEditKind Microsoft.CodeAnalysis.GeneratorAttribute.GeneratorAttribute(string! firstLanguage, params string![]! additionalLanguages) -> void Microsoft.CodeAnalysis.GeneratorAttribute.Languages.get -> string![]! Microsoft.CodeAnalysis.GeneratorDriver.ReplaceAdditionalText(Microsoft.CodeAnalysis.AdditionalText! oldText, Microsoft.CodeAnalysis.AdditionalText! newText) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedAnalyzerConfigOptions(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedParseOptions(Microsoft.CodeAnalysis.ParseOptions! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriverOptions Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions() -> void Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions(Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind disabledOutputs) -> void Microsoft.CodeAnalysis.GeneratorExtensions Microsoft.CodeAnalysis.IFieldSymbol.FixedSize.get -> int Microsoft.CodeAnalysis.IFieldSymbol.IsExplicitlyNamedTupleElement.get -> bool Microsoft.CodeAnalysis.GeneratorExecutionContext.SyntaxContextReceiver.get -> Microsoft.CodeAnalysis.ISyntaxContextReceiver? Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForSyntaxNotifications(Microsoft.CodeAnalysis.SyntaxContextReceiverCreator! receiverCreator) -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext Microsoft.CodeAnalysis.GeneratorSyntaxContext.GeneratorSyntaxContext() -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext.Node.get -> Microsoft.CodeAnalysis.SyntaxNode! Microsoft.CodeAnalysis.GeneratorSyntaxContext.SemanticModel.get -> Microsoft.CodeAnalysis.SemanticModel! Microsoft.CodeAnalysis.IIncrementalGenerator Microsoft.CodeAnalysis.IIncrementalGenerator.Initialize(Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext context) -> void Microsoft.CodeAnalysis.IMethodSymbol.IsPartialDefinition.get -> bool Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AdditionalTextsProvider.get -> Microsoft.CodeAnalysis.IncrementalValuesProvider<Microsoft.CodeAnalysis.AdditionalText!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AnalyzerConfigOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.CompilationProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Compilation!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.IncrementalGeneratorInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.ParseOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.ParseOptions!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(System.Action<Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.SyntaxProvider.get -> Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Implementation = 4 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.None = 0 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.PostInit = 2 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Source = 1 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.IncrementalGeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalValueProvider<TValue> Microsoft.CodeAnalysis.IncrementalValueProvider<TValue>.IncrementalValueProvider() -> void Microsoft.CodeAnalysis.IncrementalValueProviderExtensions Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues> Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues>.IncrementalValuesProvider() -> void Microsoft.CodeAnalysis.ISyntaxContextReceiver Microsoft.CodeAnalysis.ISyntaxContextReceiver.OnVisitSyntaxNode(Microsoft.CodeAnalysis.GeneratorSyntaxContext context) -> void Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForPostInitialization(System.Action<Microsoft.CodeAnalysis.GeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.GeneratorPostInitializationContext.GeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IMethodSymbol.MethodImplementationFlags.get -> System.Reflection.MethodImplAttributes Microsoft.CodeAnalysis.ITypeSymbol.IsRecord.get -> bool Microsoft.CodeAnalysis.LineMapping Microsoft.CodeAnalysis.LineMapping.CharacterOffset.get -> int? Microsoft.CodeAnalysis.LineMapping.Equals(Microsoft.CodeAnalysis.LineMapping other) -> bool Microsoft.CodeAnalysis.LineMapping.IsHidden.get -> bool Microsoft.CodeAnalysis.LineMapping.LineMapping() -> void Microsoft.CodeAnalysis.LineMapping.LineMapping(Microsoft.CodeAnalysis.Text.LinePositionSpan span, int? characterOffset, Microsoft.CodeAnalysis.FileLinePositionSpan mappedSpan) -> void Microsoft.CodeAnalysis.LineMapping.MappedSpan.get -> Microsoft.CodeAnalysis.FileLinePositionSpan Microsoft.CodeAnalysis.LineMapping.Span.get -> Microsoft.CodeAnalysis.Text.LinePositionSpan override Microsoft.CodeAnalysis.LineMapping.Equals(object? obj) -> bool override Microsoft.CodeAnalysis.LineMapping.GetHashCode() -> int override Microsoft.CodeAnalysis.LineMapping.ToString() -> string? Microsoft.CodeAnalysis.Operations.ISwitchExpressionOperation.IsExhaustive.get -> bool Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument> Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.OperationWalker() -> void Microsoft.CodeAnalysis.SourceProductionContext Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.SourceProductionContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.SourceProductionContext.ReportDiagnostic(Microsoft.CodeAnalysis.Diagnostic! diagnostic) -> void Microsoft.CodeAnalysis.SourceProductionContext.SourceProductionContext() -> void Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordClassName = 31 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind const Microsoft.CodeAnalysis.WellKnownDiagnosticTags.CompilationEnd = "CompilationEnd" -> string! Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordStructName = 32 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind Microsoft.CodeAnalysis.SyntaxContextReceiverCreator Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNode.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNodeOrToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNodeOrToken other) -> bool Microsoft.CodeAnalysis.SyntaxToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxToken token) -> bool Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.SyntaxValueProvider.CreateSyntaxProvider<T>(System.Func<Microsoft.CodeAnalysis.SyntaxNode!, System.Threading.CancellationToken, bool>! predicate, System.Func<Microsoft.CodeAnalysis.GeneratorSyntaxContext, System.Threading.CancellationToken, T>! transform) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<T> Microsoft.CodeAnalysis.SyntaxValueProvider.SyntaxValueProvider() -> void override Microsoft.CodeAnalysis.Text.TextChangeRange.ToString() -> string! readonly Microsoft.CodeAnalysis.GeneratorDriverOptions.DisabledOutputs -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Compare(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> int static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Equals(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> bool override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.DefaultVisit(Microsoft.CodeAnalysis.IOperation! operation, TArgument argument) -> object? override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.Visit(Microsoft.CodeAnalysis.IOperation? operation, TArgument argument) -> object? static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator !=(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator ==(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator !=(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator ==(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.GeneratorExtensions.AsSourceGenerator(this Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator! static Microsoft.CodeAnalysis.GeneratorExtensions.GetGeneratorType(this Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type! static Microsoft.CodeAnalysis.LineMapping.operator !=(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.LineMapping.operator ==(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Collect<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source) -> Microsoft.CodeAnalysis.IncrementalValueProvider<System.Collections.Immutable.ImmutableArray<TSource>> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValueProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Where<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, bool>! predicate) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> abstract Microsoft.CodeAnalysis.Compilation.GetUsedAssemblyReferences(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.MetadataReference!>
*REMOVED*Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode! other) -> bool abstract Microsoft.CodeAnalysis.SyntaxTree.GetLineMappings(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.LineMapping>! const Microsoft.CodeAnalysis.WellKnownMemberNames.PrintMembersMethodName = "PrintMembers" -> string! Microsoft.CodeAnalysis.Compilation.EmitDifference(Microsoft.CodeAnalysis.Emit.EmitBaseline! baseline, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Emit.SemanticEdit>! edits, System.Func<Microsoft.CodeAnalysis.ISymbol!, bool>! isAddedSymbol, System.IO.Stream! metadataStream, System.IO.Stream! ilStream, System.IO.Stream! pdbStream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult! Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.ChangedTypes.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.TypeDefinitionHandle> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedMethods.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.MethodDefinitionHandle> Microsoft.CodeAnalysis.Emit.SemanticEditKind.Replace = 4 -> Microsoft.CodeAnalysis.Emit.SemanticEditKind Microsoft.CodeAnalysis.GeneratorAttribute.GeneratorAttribute(string! firstLanguage, params string![]! additionalLanguages) -> void Microsoft.CodeAnalysis.GeneratorAttribute.Languages.get -> string![]! Microsoft.CodeAnalysis.GeneratorDriver.ReplaceAdditionalText(Microsoft.CodeAnalysis.AdditionalText! oldText, Microsoft.CodeAnalysis.AdditionalText! newText) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedAnalyzerConfigOptions(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedParseOptions(Microsoft.CodeAnalysis.ParseOptions! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriverOptions Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions() -> void Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions(Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind disabledOutputs) -> void Microsoft.CodeAnalysis.GeneratorExtensions Microsoft.CodeAnalysis.IFieldSymbol.FixedSize.get -> int Microsoft.CodeAnalysis.IFieldSymbol.IsExplicitlyNamedTupleElement.get -> bool Microsoft.CodeAnalysis.GeneratorExecutionContext.SyntaxContextReceiver.get -> Microsoft.CodeAnalysis.ISyntaxContextReceiver? Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForSyntaxNotifications(Microsoft.CodeAnalysis.SyntaxContextReceiverCreator! receiverCreator) -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext Microsoft.CodeAnalysis.GeneratorSyntaxContext.GeneratorSyntaxContext() -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext.Node.get -> Microsoft.CodeAnalysis.SyntaxNode! Microsoft.CodeAnalysis.GeneratorSyntaxContext.SemanticModel.get -> Microsoft.CodeAnalysis.SemanticModel! Microsoft.CodeAnalysis.IIncrementalGenerator Microsoft.CodeAnalysis.IIncrementalGenerator.Initialize(Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext context) -> void Microsoft.CodeAnalysis.IMethodSymbol.IsPartialDefinition.get -> bool Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AdditionalTextsProvider.get -> Microsoft.CodeAnalysis.IncrementalValuesProvider<Microsoft.CodeAnalysis.AdditionalText!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AnalyzerConfigOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.CompilationProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Compilation!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.IncrementalGeneratorInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.MetadataReferencesProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.MetadataReference!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.ParseOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.ParseOptions!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(System.Action<Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.SyntaxProvider.get -> Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Implementation = 4 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.None = 0 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.PostInit = 2 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Source = 1 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.IncrementalGeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalValueProvider<TValue> Microsoft.CodeAnalysis.IncrementalValueProvider<TValue>.IncrementalValueProvider() -> void Microsoft.CodeAnalysis.IncrementalValueProviderExtensions Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues> Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues>.IncrementalValuesProvider() -> void Microsoft.CodeAnalysis.ISyntaxContextReceiver Microsoft.CodeAnalysis.ISyntaxContextReceiver.OnVisitSyntaxNode(Microsoft.CodeAnalysis.GeneratorSyntaxContext context) -> void Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForPostInitialization(System.Action<Microsoft.CodeAnalysis.GeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.GeneratorPostInitializationContext.GeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IMethodSymbol.MethodImplementationFlags.get -> System.Reflection.MethodImplAttributes Microsoft.CodeAnalysis.ITypeSymbol.IsRecord.get -> bool Microsoft.CodeAnalysis.LineMapping Microsoft.CodeAnalysis.LineMapping.CharacterOffset.get -> int? Microsoft.CodeAnalysis.LineMapping.Equals(Microsoft.CodeAnalysis.LineMapping other) -> bool Microsoft.CodeAnalysis.LineMapping.IsHidden.get -> bool Microsoft.CodeAnalysis.LineMapping.LineMapping() -> void Microsoft.CodeAnalysis.LineMapping.LineMapping(Microsoft.CodeAnalysis.Text.LinePositionSpan span, int? characterOffset, Microsoft.CodeAnalysis.FileLinePositionSpan mappedSpan) -> void Microsoft.CodeAnalysis.LineMapping.MappedSpan.get -> Microsoft.CodeAnalysis.FileLinePositionSpan Microsoft.CodeAnalysis.LineMapping.Span.get -> Microsoft.CodeAnalysis.Text.LinePositionSpan override Microsoft.CodeAnalysis.LineMapping.Equals(object? obj) -> bool override Microsoft.CodeAnalysis.LineMapping.GetHashCode() -> int override Microsoft.CodeAnalysis.LineMapping.ToString() -> string? Microsoft.CodeAnalysis.Operations.ISwitchExpressionOperation.IsExhaustive.get -> bool Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument> Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.OperationWalker() -> void Microsoft.CodeAnalysis.SourceProductionContext Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.SourceProductionContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.SourceProductionContext.ReportDiagnostic(Microsoft.CodeAnalysis.Diagnostic! diagnostic) -> void Microsoft.CodeAnalysis.SourceProductionContext.SourceProductionContext() -> void Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordClassName = 31 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind const Microsoft.CodeAnalysis.WellKnownDiagnosticTags.CompilationEnd = "CompilationEnd" -> string! Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordStructName = 32 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind Microsoft.CodeAnalysis.SyntaxContextReceiverCreator Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNode.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNodeOrToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNodeOrToken other) -> bool Microsoft.CodeAnalysis.SyntaxToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxToken token) -> bool Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.SyntaxValueProvider.CreateSyntaxProvider<T>(System.Func<Microsoft.CodeAnalysis.SyntaxNode!, System.Threading.CancellationToken, bool>! predicate, System.Func<Microsoft.CodeAnalysis.GeneratorSyntaxContext, System.Threading.CancellationToken, T>! transform) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<T> Microsoft.CodeAnalysis.SyntaxValueProvider.SyntaxValueProvider() -> void override Microsoft.CodeAnalysis.Text.TextChangeRange.ToString() -> string! readonly Microsoft.CodeAnalysis.GeneratorDriverOptions.DisabledOutputs -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Compare(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> int static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Equals(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> bool override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.DefaultVisit(Microsoft.CodeAnalysis.IOperation! operation, TArgument argument) -> object? override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.Visit(Microsoft.CodeAnalysis.IOperation? operation, TArgument argument) -> object? static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator !=(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator ==(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator !=(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator ==(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.GeneratorExtensions.AsSourceGenerator(this Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator! static Microsoft.CodeAnalysis.GeneratorExtensions.GetGeneratorType(this Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type! static Microsoft.CodeAnalysis.LineMapping.operator !=(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.LineMapping.operator ==(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Collect<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source) -> Microsoft.CodeAnalysis.IncrementalValueProvider<System.Collections.Immutable.ImmutableArray<TSource>> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValueProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Where<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, bool>! predicate) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> abstract Microsoft.CodeAnalysis.Compilation.GetUsedAssemblyReferences(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.MetadataReference!>
1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/Core/Portable/SourceGeneration/IncrementalContexts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to an incremental generator when <see cref="IIncrementalGenerator.Initialize(IncrementalGeneratorInitializationContext)"/> is called /// </summary> public readonly struct IncrementalGeneratorInitializationContext { private readonly ArrayBuilder<ISyntaxInputNode> _syntaxInputBuilder; private readonly ArrayBuilder<IIncrementalGeneratorOutputNode> _outputNodes; internal IncrementalGeneratorInitializationContext(ArrayBuilder<ISyntaxInputNode> syntaxInputBuilder, ArrayBuilder<IIncrementalGeneratorOutputNode> outputNodes) { _syntaxInputBuilder = syntaxInputBuilder; _outputNodes = outputNodes; } public SyntaxValueProvider SyntaxProvider => new SyntaxValueProvider(_syntaxInputBuilder, RegisterOutput); public IncrementalValueProvider<Compilation> CompilationProvider => new IncrementalValueProvider<Compilation>(SharedInputNodes.Compilation.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<ParseOptions> ParseOptionsProvider => new IncrementalValueProvider<ParseOptions>(SharedInputNodes.ParseOptions.WithRegisterOutput(RegisterOutput)); public IncrementalValuesProvider<AdditionalText> AdditionalTextsProvider => new IncrementalValuesProvider<AdditionalText>(SharedInputNodes.AdditionalTexts.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<AnalyzerConfigOptionsProvider> AnalyzerConfigOptionsProvider => new IncrementalValueProvider<AnalyzerConfigOptionsProvider>(SharedInputNodes.AnalyzerConfigOptions.WithRegisterOutput(RegisterOutput)); public void RegisterSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source); public void RegisterSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source); public void RegisterImplementationSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation); public void RegisterImplementationSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation); public void RegisterPostInitializationOutput(Action<IncrementalGeneratorPostInitializationContext> callback) => _outputNodes.Add(new PostInitOutputNode(callback.WrapUserAction())); private void RegisterOutput(IIncrementalGeneratorOutputNode outputNode) { if (!_outputNodes.Contains(outputNode)) { _outputNodes.Add(outputNode); } } private static void RegisterSourceOutput<TSource>(IIncrementalGeneratorNode<TSource> node, Action<SourceProductionContext, TSource> action, IncrementalGeneratorOutputKind kind) { node.RegisterOutput(new SourceOutputNode<TSource>(node, action.WrapUserAction(), kind)); } } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/> /// </summary> public readonly struct IncrementalGeneratorPostInitializationContext { internal readonly AdditionalSourcesCollection AdditionalSources; internal IncrementalGeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { AdditionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => AdditionalSources.Add(hintName, sourceText); } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> public readonly struct SourceProductionContext { internal readonly ArrayBuilder<GeneratedSourceText> Sources; internal readonly DiagnosticBag Diagnostics; internal SourceProductionContext(ArrayBuilder<GeneratedSourceText> sources, DiagnosticBag diagnostics, CancellationToken cancellationToken) { CancellationToken = cancellationToken; Sources = sources; Diagnostics = diagnostics; } public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => Sources.Add(new GeneratedSourceText(hintName, sourceText)); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => Diagnostics.Add(diagnostic); } // https://github.com/dotnet/roslyn/issues/53608 right now we only support generating source + diagnostics, but actively want to support generation of other things internal readonly struct IncrementalExecutionContext { internal readonly DiagnosticBag Diagnostics; internal readonly AdditionalSourcesCollection Sources; internal readonly DriverStateTable.Builder? TableBuilder; public IncrementalExecutionContext(DriverStateTable.Builder? tableBuilder, AdditionalSourcesCollection sources) { TableBuilder = tableBuilder; Sources = sources; Diagnostics = DiagnosticBag.GetInstance(); } internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (Sources.ToImmutableAndFree(), Diagnostics.ToReadOnlyAndFree()); internal void Free() { Sources.Free(); Diagnostics.Free(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to an incremental generator when <see cref="IIncrementalGenerator.Initialize(IncrementalGeneratorInitializationContext)"/> is called /// </summary> public readonly struct IncrementalGeneratorInitializationContext { private readonly ArrayBuilder<ISyntaxInputNode> _syntaxInputBuilder; private readonly ArrayBuilder<IIncrementalGeneratorOutputNode> _outputNodes; internal IncrementalGeneratorInitializationContext(ArrayBuilder<ISyntaxInputNode> syntaxInputBuilder, ArrayBuilder<IIncrementalGeneratorOutputNode> outputNodes) { _syntaxInputBuilder = syntaxInputBuilder; _outputNodes = outputNodes; } public SyntaxValueProvider SyntaxProvider => new SyntaxValueProvider(_syntaxInputBuilder, RegisterOutput); public IncrementalValueProvider<Compilation> CompilationProvider => new IncrementalValueProvider<Compilation>(SharedInputNodes.Compilation.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<ParseOptions> ParseOptionsProvider => new IncrementalValueProvider<ParseOptions>(SharedInputNodes.ParseOptions.WithRegisterOutput(RegisterOutput)); public IncrementalValuesProvider<AdditionalText> AdditionalTextsProvider => new IncrementalValuesProvider<AdditionalText>(SharedInputNodes.AdditionalTexts.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<AnalyzerConfigOptionsProvider> AnalyzerConfigOptionsProvider => new IncrementalValueProvider<AnalyzerConfigOptionsProvider>(SharedInputNodes.AnalyzerConfigOptions.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<MetadataReference> MetadataReferencesProvider => new IncrementalValueProvider<MetadataReference>(SharedInputNodes.MetadataReferences.WithRegisterOutput(RegisterOutput)); public void RegisterSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source); public void RegisterSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source); public void RegisterImplementationSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation); public void RegisterImplementationSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation); public void RegisterPostInitializationOutput(Action<IncrementalGeneratorPostInitializationContext> callback) => _outputNodes.Add(new PostInitOutputNode(callback.WrapUserAction())); private void RegisterOutput(IIncrementalGeneratorOutputNode outputNode) { if (!_outputNodes.Contains(outputNode)) { _outputNodes.Add(outputNode); } } private static void RegisterSourceOutput<TSource>(IIncrementalGeneratorNode<TSource> node, Action<SourceProductionContext, TSource> action, IncrementalGeneratorOutputKind kind) { node.RegisterOutput(new SourceOutputNode<TSource>(node, action.WrapUserAction(), kind)); } } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/> /// </summary> public readonly struct IncrementalGeneratorPostInitializationContext { internal readonly AdditionalSourcesCollection AdditionalSources; internal IncrementalGeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { AdditionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => AdditionalSources.Add(hintName, sourceText); } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> public readonly struct SourceProductionContext { internal readonly ArrayBuilder<GeneratedSourceText> Sources; internal readonly DiagnosticBag Diagnostics; internal SourceProductionContext(ArrayBuilder<GeneratedSourceText> sources, DiagnosticBag diagnostics, CancellationToken cancellationToken) { CancellationToken = cancellationToken; Sources = sources; Diagnostics = diagnostics; } public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => Sources.Add(new GeneratedSourceText(hintName, sourceText)); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => Diagnostics.Add(diagnostic); } // https://github.com/dotnet/roslyn/issues/53608 right now we only support generating source + diagnostics, but actively want to support generation of other things internal readonly struct IncrementalExecutionContext { internal readonly DiagnosticBag Diagnostics; internal readonly AdditionalSourcesCollection Sources; internal readonly DriverStateTable.Builder? TableBuilder; public IncrementalExecutionContext(DriverStateTable.Builder? tableBuilder, AdditionalSourcesCollection sources) { TableBuilder = tableBuilder; Sources = sources; Diagnostics = DiagnosticBag.GetInstance(); } internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (Sources.ToImmutableAndFree(), Diagnostics.ToReadOnlyAndFree()); internal void Free() { Sources.Free(); Diagnostics.Free(); } } }
1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/Core/Portable/SourceGeneration/Nodes/SharedInputNodes.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Holds input nodes that are shared between generators and always exist /// </summary> internal static class SharedInputNodes { public static readonly InputNode<Compilation> Compilation = new InputNode<Compilation>(b => ImmutableArray.Create(b.Compilation)); public static readonly InputNode<ParseOptions> ParseOptions = new InputNode<ParseOptions>(b => ImmutableArray.Create(b.DriverState.ParseOptions)); public static readonly InputNode<AdditionalText> AdditionalTexts = new InputNode<AdditionalText>(b => b.DriverState.AdditionalTexts); public static readonly InputNode<SyntaxTree> SyntaxTrees = new InputNode<SyntaxTree>(b => b.Compilation.SyntaxTrees.ToImmutableArray()); public static readonly InputNode<AnalyzerConfigOptionsProvider> AnalyzerConfigOptions = new InputNode<AnalyzerConfigOptionsProvider>(b => ImmutableArray.Create(b.DriverState.OptionsProvider)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Holds input nodes that are shared between generators and always exist /// </summary> internal static class SharedInputNodes { public static readonly InputNode<Compilation> Compilation = new InputNode<Compilation>(b => ImmutableArray.Create(b.Compilation)); public static readonly InputNode<ParseOptions> ParseOptions = new InputNode<ParseOptions>(b => ImmutableArray.Create(b.DriverState.ParseOptions)); public static readonly InputNode<AdditionalText> AdditionalTexts = new InputNode<AdditionalText>(b => b.DriverState.AdditionalTexts); public static readonly InputNode<SyntaxTree> SyntaxTrees = new InputNode<SyntaxTree>(b => b.Compilation.SyntaxTrees.ToImmutableArray()); public static readonly InputNode<AnalyzerConfigOptionsProvider> AnalyzerConfigOptions = new InputNode<AnalyzerConfigOptionsProvider>(b => ImmutableArray.Create(b.DriverState.OptionsProvider)); public static readonly InputNode<MetadataReference> MetadataReferences = new InputNode<MetadataReference>(b => b.Compilation.ExternalReferences); } }
1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Workspaces/Core/Portable/Remote/RemoteSupportedLanguages.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Remote { internal static class RemoteSupportedLanguages { public static bool IsSupported(this string language) { return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Remote { internal static class RemoteSupportedLanguages { public static bool IsSupported(this string language) { return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic; } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.AnalysisData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FlowAnalysis.SymbolUsageAnalysis { internal static partial class SymbolUsageAnalysis { /// <summary> /// Core analysis data to drive the operation <see cref="Walker"/> /// for operation tree based analysis OR control flow graph based analysis. /// </summary> private abstract class AnalysisData : IDisposable { /// <summary> /// Pooled <see cref="BasicBlockAnalysisData"/> allocated during analysis with the /// current <see cref="AnalysisData"/> instance, which will be freed during <see cref="Dispose"/>. /// </summary> private readonly ArrayBuilder<BasicBlockAnalysisData> _allocatedBasicBlockAnalysisDatas; /// <summary> /// Set of locals/parameters which are passed by reference to other method calls. /// </summary> private readonly PooledHashSet<ISymbol> _referenceTakenSymbolsBuilder; protected AnalysisData() { _allocatedBasicBlockAnalysisDatas = ArrayBuilder<BasicBlockAnalysisData>.GetInstance(); _referenceTakenSymbolsBuilder = PooledHashSet<ISymbol>.GetInstance(); CurrentBlockAnalysisData = CreateBlockAnalysisData(); AdditionalConditionalBranchAnalysisData = CreateBlockAnalysisData(); } /// <summary> /// Map from each (symbol, write) to a boolean indicating if the value assigned /// at the write is read on some control flow path. /// For example, consider the following code: /// <code> /// int x = 0; /// x = 1; /// Console.WriteLine(x); /// </code> /// This map will have two entries for 'x': /// 1. Key = (symbol: x, write: 'int x = 0') /// Value = 'false', because value assigned to 'x' here **is never** read. /// 2. Key = (symbol: x, write: 'x = 1') /// Value = 'true', because value assigned to 'x' here **may be** read on /// some control flow path. /// </summary> protected abstract PooledDictionary<(ISymbol symbol, IOperation operation), bool> SymbolsWriteBuilder { get; } /// <summary> /// Set of locals/parameters that are read at least once. /// </summary> protected abstract PooledHashSet<ISymbol> SymbolsReadBuilder { get; } /// <summary> /// Set of lambda/local functions whose invocations are currently being analyzed to prevent /// infinite recursion for analyzing code with recursive lambda/local function calls. /// </summary> protected abstract PooledHashSet<IMethodSymbol> LambdaOrLocalFunctionsBeingAnalyzed { get; } /// <summary> /// Current block analysis data used for analysis. /// </summary> public BasicBlockAnalysisData CurrentBlockAnalysisData { get; } /// <summary> /// Block analysis data used for an additional conditional branch. /// </summary> public BasicBlockAnalysisData AdditionalConditionalBranchAnalysisData { get; } /// <summary> /// Creates an immutable <see cref="SymbolUsageResult"/> for the current analysis data. /// </summary> public SymbolUsageResult ToResult() => new(SymbolsWriteBuilder.ToImmutableDictionary(), SymbolsReadBuilder.ToImmutableHashSet()); public BasicBlockAnalysisData AnalyzeLocalFunctionInvocation(IMethodSymbol localFunction, CancellationToken cancellationToken) { Debug.Assert(localFunction.IsLocalFunction()); // Use the original definition of the local function for flow analysis. localFunction = localFunction.OriginalDefinition; if (!LambdaOrLocalFunctionsBeingAnalyzed.Add(localFunction)) { ResetState(); return CurrentBlockAnalysisData; } else { var result = AnalyzeLocalFunctionInvocationCore(localFunction, cancellationToken); LambdaOrLocalFunctionsBeingAnalyzed.Remove(localFunction); return result; } } public BasicBlockAnalysisData AnalyzeLambdaInvocation(IFlowAnonymousFunctionOperation lambda, CancellationToken cancellationToken) { if (!LambdaOrLocalFunctionsBeingAnalyzed.Add(lambda.Symbol)) { ResetState(); return CurrentBlockAnalysisData; } else { var result = AnalyzeLambdaInvocationCore(lambda, cancellationToken); LambdaOrLocalFunctionsBeingAnalyzed.Remove(lambda.Symbol); return result; } } protected abstract BasicBlockAnalysisData AnalyzeLocalFunctionInvocationCore(IMethodSymbol localFunction, CancellationToken cancellationToken); protected abstract BasicBlockAnalysisData AnalyzeLambdaInvocationCore(IFlowAnonymousFunctionOperation lambda, CancellationToken cancellationToken); // Methods specific to flow capture analysis for CFG based dataflow analysis. public abstract bool IsLValueFlowCapture(CaptureId captureId); public abstract bool IsRValueFlowCapture(CaptureId captureId); public abstract void OnLValueCaptureFound(ISymbol symbol, IOperation operation, CaptureId captureId); public abstract void OnLValueDereferenceFound(CaptureId captureId); // Methods specific to delegate analysis to track potential delegate invocation targets for CFG based dataflow analysis. public abstract bool IsTrackingDelegateCreationTargets { get; } public abstract void SetTargetsFromSymbolForDelegate(IOperation write, ISymbol symbol); public abstract void SetLambdaTargetForDelegate(IOperation write, IFlowAnonymousFunctionOperation lambdaTarget); public abstract void SetLocalFunctionTargetForDelegate(IOperation write, IMethodReferenceOperation localFunctionTarget); public abstract void SetEmptyInvocationTargetsForDelegate(IOperation write); public abstract bool TryGetDelegateInvocationTargets(IOperation write, out ImmutableHashSet<IOperation> targets); protected static PooledDictionary<(ISymbol Symbol, IOperation Write), bool> CreateSymbolsWriteMap( ImmutableArray<IParameterSymbol> parameters) { var symbolsWriteMap = PooledDictionary<(ISymbol Symbol, IOperation Write), bool>.GetInstance(); return UpdateSymbolsWriteMap(symbolsWriteMap, parameters); } protected static PooledDictionary<(ISymbol Symbol, IOperation Write), bool> UpdateSymbolsWriteMap( PooledDictionary<(ISymbol Symbol, IOperation Write), bool> symbolsWriteMap, ImmutableArray<IParameterSymbol> parameters) { // Mark parameters as being written from the value provided at the call site. // Note that the write operation is "null" as there is no corresponding IOperation for parameter definition. foreach (var parameter in parameters) { (ISymbol, IOperation) key = (parameter, null); if (!symbolsWriteMap.ContainsKey(key)) { symbolsWriteMap.Add(key, false); } } return symbolsWriteMap; } public BasicBlockAnalysisData CreateBlockAnalysisData() { var instance = BasicBlockAnalysisData.GetInstance(); TrackAllocatedBlockAnalysisData(instance); return instance; } public void TrackAllocatedBlockAnalysisData(BasicBlockAnalysisData allocatedData) => _allocatedBasicBlockAnalysisDatas.Add(allocatedData); public void OnReadReferenceFound(ISymbol symbol) { if (symbol.Kind == SymbolKind.Discard) { return; } // Mark all the current reaching writes of symbol as read. if (SymbolsWriteBuilder.Count != 0) { var currentWrites = CurrentBlockAnalysisData.GetCurrentWrites(symbol); foreach (var write in currentWrites) { SymbolsWriteBuilder[(symbol, write)] = true; } } // Mark the current symbol as read. SymbolsReadBuilder.Add(symbol); } public void OnWriteReferenceFound(ISymbol symbol, IOperation operation, bool maybeWritten, bool isRef) { var symbolAndWrite = (symbol, operation); if (symbol.Kind == SymbolKind.Discard) { // Skip discard symbols and also for already processed writes (back edge from loops). return; } if (_referenceTakenSymbolsBuilder.Contains(symbol)) { // Skip tracking writes for reference taken symbols as the written value may be read from a different variable. return; } // Add a new write for the given symbol at the given operation. CurrentBlockAnalysisData.OnWriteReferenceFound(symbol, operation, maybeWritten); if (isRef) { _referenceTakenSymbolsBuilder.Add(symbol); } // Only mark as unused write if we are processing it for the first time (not from back edge for loops) if (!SymbolsWriteBuilder.ContainsKey(symbolAndWrite) && !maybeWritten) { SymbolsWriteBuilder.Add((symbol, operation), false); } } /// <summary> /// Resets all the currently tracked symbol writes to be conservatively marked as read. /// </summary> public void ResetState() { foreach (var symbol in SymbolsWriteBuilder.Keys.Select(d => d.symbol).ToArray()) { OnReadReferenceFound(symbol); } } public void SetCurrentBlockAnalysisDataFrom(BasicBlockAnalysisData newBlockAnalysisData) { Debug.Assert(newBlockAnalysisData != null); CurrentBlockAnalysisData.SetAnalysisDataFrom(newBlockAnalysisData); } public virtual void Dispose() { foreach (var instance in _allocatedBasicBlockAnalysisDatas) { instance.Dispose(); } _allocatedBasicBlockAnalysisDatas.Free(); _referenceTakenSymbolsBuilder.Free(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FlowAnalysis.SymbolUsageAnalysis { internal static partial class SymbolUsageAnalysis { /// <summary> /// Core analysis data to drive the operation <see cref="Walker"/> /// for operation tree based analysis OR control flow graph based analysis. /// </summary> private abstract class AnalysisData : IDisposable { /// <summary> /// Pooled <see cref="BasicBlockAnalysisData"/> allocated during analysis with the /// current <see cref="AnalysisData"/> instance, which will be freed during <see cref="Dispose"/>. /// </summary> private readonly ArrayBuilder<BasicBlockAnalysisData> _allocatedBasicBlockAnalysisDatas; /// <summary> /// Set of locals/parameters which are passed by reference to other method calls. /// </summary> private readonly PooledHashSet<ISymbol> _referenceTakenSymbolsBuilder; protected AnalysisData() { _allocatedBasicBlockAnalysisDatas = ArrayBuilder<BasicBlockAnalysisData>.GetInstance(); _referenceTakenSymbolsBuilder = PooledHashSet<ISymbol>.GetInstance(); CurrentBlockAnalysisData = CreateBlockAnalysisData(); AdditionalConditionalBranchAnalysisData = CreateBlockAnalysisData(); } /// <summary> /// Map from each (symbol, write) to a boolean indicating if the value assigned /// at the write is read on some control flow path. /// For example, consider the following code: /// <code> /// int x = 0; /// x = 1; /// Console.WriteLine(x); /// </code> /// This map will have two entries for 'x': /// 1. Key = (symbol: x, write: 'int x = 0') /// Value = 'false', because value assigned to 'x' here **is never** read. /// 2. Key = (symbol: x, write: 'x = 1') /// Value = 'true', because value assigned to 'x' here **may be** read on /// some control flow path. /// </summary> protected abstract PooledDictionary<(ISymbol symbol, IOperation operation), bool> SymbolsWriteBuilder { get; } /// <summary> /// Set of locals/parameters that are read at least once. /// </summary> protected abstract PooledHashSet<ISymbol> SymbolsReadBuilder { get; } /// <summary> /// Set of lambda/local functions whose invocations are currently being analyzed to prevent /// infinite recursion for analyzing code with recursive lambda/local function calls. /// </summary> protected abstract PooledHashSet<IMethodSymbol> LambdaOrLocalFunctionsBeingAnalyzed { get; } /// <summary> /// Current block analysis data used for analysis. /// </summary> public BasicBlockAnalysisData CurrentBlockAnalysisData { get; } /// <summary> /// Block analysis data used for an additional conditional branch. /// </summary> public BasicBlockAnalysisData AdditionalConditionalBranchAnalysisData { get; } /// <summary> /// Creates an immutable <see cref="SymbolUsageResult"/> for the current analysis data. /// </summary> public SymbolUsageResult ToResult() => new(SymbolsWriteBuilder.ToImmutableDictionary(), SymbolsReadBuilder.ToImmutableHashSet()); public BasicBlockAnalysisData AnalyzeLocalFunctionInvocation(IMethodSymbol localFunction, CancellationToken cancellationToken) { Debug.Assert(localFunction.IsLocalFunction()); // Use the original definition of the local function for flow analysis. localFunction = localFunction.OriginalDefinition; if (!LambdaOrLocalFunctionsBeingAnalyzed.Add(localFunction)) { ResetState(); return CurrentBlockAnalysisData; } else { var result = AnalyzeLocalFunctionInvocationCore(localFunction, cancellationToken); LambdaOrLocalFunctionsBeingAnalyzed.Remove(localFunction); return result; } } public BasicBlockAnalysisData AnalyzeLambdaInvocation(IFlowAnonymousFunctionOperation lambda, CancellationToken cancellationToken) { if (!LambdaOrLocalFunctionsBeingAnalyzed.Add(lambda.Symbol)) { ResetState(); return CurrentBlockAnalysisData; } else { var result = AnalyzeLambdaInvocationCore(lambda, cancellationToken); LambdaOrLocalFunctionsBeingAnalyzed.Remove(lambda.Symbol); return result; } } protected abstract BasicBlockAnalysisData AnalyzeLocalFunctionInvocationCore(IMethodSymbol localFunction, CancellationToken cancellationToken); protected abstract BasicBlockAnalysisData AnalyzeLambdaInvocationCore(IFlowAnonymousFunctionOperation lambda, CancellationToken cancellationToken); // Methods specific to flow capture analysis for CFG based dataflow analysis. public abstract bool IsLValueFlowCapture(CaptureId captureId); public abstract bool IsRValueFlowCapture(CaptureId captureId); public abstract void OnLValueCaptureFound(ISymbol symbol, IOperation operation, CaptureId captureId); public abstract void OnLValueDereferenceFound(CaptureId captureId); // Methods specific to delegate analysis to track potential delegate invocation targets for CFG based dataflow analysis. public abstract bool IsTrackingDelegateCreationTargets { get; } public abstract void SetTargetsFromSymbolForDelegate(IOperation write, ISymbol symbol); public abstract void SetLambdaTargetForDelegate(IOperation write, IFlowAnonymousFunctionOperation lambdaTarget); public abstract void SetLocalFunctionTargetForDelegate(IOperation write, IMethodReferenceOperation localFunctionTarget); public abstract void SetEmptyInvocationTargetsForDelegate(IOperation write); public abstract bool TryGetDelegateInvocationTargets(IOperation write, out ImmutableHashSet<IOperation> targets); protected static PooledDictionary<(ISymbol Symbol, IOperation Write), bool> CreateSymbolsWriteMap( ImmutableArray<IParameterSymbol> parameters) { var symbolsWriteMap = PooledDictionary<(ISymbol Symbol, IOperation Write), bool>.GetInstance(); return UpdateSymbolsWriteMap(symbolsWriteMap, parameters); } protected static PooledDictionary<(ISymbol Symbol, IOperation Write), bool> UpdateSymbolsWriteMap( PooledDictionary<(ISymbol Symbol, IOperation Write), bool> symbolsWriteMap, ImmutableArray<IParameterSymbol> parameters) { // Mark parameters as being written from the value provided at the call site. // Note that the write operation is "null" as there is no corresponding IOperation for parameter definition. foreach (var parameter in parameters) { (ISymbol, IOperation) key = (parameter, null); if (!symbolsWriteMap.ContainsKey(key)) { symbolsWriteMap.Add(key, false); } } return symbolsWriteMap; } public BasicBlockAnalysisData CreateBlockAnalysisData() { var instance = BasicBlockAnalysisData.GetInstance(); TrackAllocatedBlockAnalysisData(instance); return instance; } public void TrackAllocatedBlockAnalysisData(BasicBlockAnalysisData allocatedData) => _allocatedBasicBlockAnalysisDatas.Add(allocatedData); public void OnReadReferenceFound(ISymbol symbol) { if (symbol.Kind == SymbolKind.Discard) { return; } // Mark all the current reaching writes of symbol as read. if (SymbolsWriteBuilder.Count != 0) { var currentWrites = CurrentBlockAnalysisData.GetCurrentWrites(symbol); foreach (var write in currentWrites) { SymbolsWriteBuilder[(symbol, write)] = true; } } // Mark the current symbol as read. SymbolsReadBuilder.Add(symbol); } public void OnWriteReferenceFound(ISymbol symbol, IOperation operation, bool maybeWritten, bool isRef) { var symbolAndWrite = (symbol, operation); if (symbol.Kind == SymbolKind.Discard) { // Skip discard symbols and also for already processed writes (back edge from loops). return; } if (_referenceTakenSymbolsBuilder.Contains(symbol)) { // Skip tracking writes for reference taken symbols as the written value may be read from a different variable. return; } // Add a new write for the given symbol at the given operation. CurrentBlockAnalysisData.OnWriteReferenceFound(symbol, operation, maybeWritten); if (isRef) { _referenceTakenSymbolsBuilder.Add(symbol); } // Only mark as unused write if we are processing it for the first time (not from back edge for loops) if (!SymbolsWriteBuilder.ContainsKey(symbolAndWrite) && !maybeWritten) { SymbolsWriteBuilder.Add((symbol, operation), false); } } /// <summary> /// Resets all the currently tracked symbol writes to be conservatively marked as read. /// </summary> public void ResetState() { foreach (var symbol in SymbolsWriteBuilder.Keys.Select(d => d.symbol).ToArray()) { OnReadReferenceFound(symbol); } } public void SetCurrentBlockAnalysisDataFrom(BasicBlockAnalysisData newBlockAnalysisData) { Debug.Assert(newBlockAnalysisData != null); CurrentBlockAnalysisData.SetAnalysisDataFrom(newBlockAnalysisData); } public virtual void Dispose() { foreach (var instance in _allocatedBasicBlockAnalysisDatas) { instance.Dispose(); } _allocatedBasicBlockAnalysisDatas.Free(); _referenceTakenSymbolsBuilder.Free(); } } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class UseExpressionBodyDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public const string FixesError = nameof(FixesError); private readonly ImmutableArray<SyntaxKind> _syntaxKinds; private static readonly ImmutableArray<UseExpressionBodyHelper> _helpers = UseExpressionBodyHelper.Helpers; public UseExpressionBodyDiagnosticAnalyzer() : base(GetSupportedDescriptorsWithOptions(), LanguageNames.CSharp) { _syntaxKinds = _helpers.SelectMany(h => h.SyntaxKinds).ToImmutableArray(); } private static ImmutableDictionary<DiagnosticDescriptor, ILanguageSpecificOption> GetSupportedDescriptorsWithOptions() { var builder = ImmutableDictionary.CreateBuilder<DiagnosticDescriptor, ILanguageSpecificOption>(); foreach (var helper in _helpers) { var descriptor = CreateDescriptorWithId(helper.DiagnosticId, helper.EnforceOnBuild, helper.UseExpressionBodyTitle, helper.UseExpressionBodyTitle); builder.Add(descriptor, helper.Option); } return builder.ToImmutable(); } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, _syntaxKinds); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var options = context.Options; var syntaxTree = context.Node.SyntaxTree; var cancellationToken = context.CancellationToken; var optionSet = options.GetAnalyzerOptionSet(syntaxTree, cancellationToken); var nodeKind = context.Node.Kind(); // Don't offer a fix on an accessor, if we would also offer it on the property/indexer. if (UseExpressionBodyForAccessorsHelper.Instance.SyntaxKinds.Contains(nodeKind)) { var grandparent = context.Node.Parent.Parent; if (grandparent.Kind() == SyntaxKind.PropertyDeclaration && AnalyzeSyntax(optionSet, grandparent, UseExpressionBodyForPropertiesHelper.Instance) != null) { return; } if (grandparent.Kind() == SyntaxKind.IndexerDeclaration && AnalyzeSyntax(optionSet, grandparent, UseExpressionBodyForIndexersHelper.Instance) != null) { return; } } foreach (var helper in _helpers) { if (helper.SyntaxKinds.Contains(nodeKind)) { var diagnostic = AnalyzeSyntax(optionSet, context.Node, helper); if (diagnostic != null) { context.ReportDiagnostic(diagnostic); return; } } } } private static Diagnostic AnalyzeSyntax( OptionSet optionSet, SyntaxNode declaration, UseExpressionBodyHelper helper) { var preferExpressionBodiedOption = optionSet.GetOption(helper.Option); var severity = preferExpressionBodiedOption.Notification.Severity; if (helper.CanOfferUseExpressionBody(optionSet, declaration, forAnalyzer: true)) { var location = severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) == ReportDiagnostic.Hidden ? declaration.GetLocation() : helper.GetDiagnosticLocation(declaration); var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); var properties = ImmutableDictionary<string, string>.Empty.Add(nameof(UseExpressionBody), ""); return DiagnosticHelper.Create( CreateDescriptorWithId(helper.DiagnosticId, helper.EnforceOnBuild, helper.UseExpressionBodyTitle, helper.UseExpressionBodyTitle), location, severity, additionalLocations: additionalLocations, properties: properties); } var (canOffer, fixesError) = helper.CanOfferUseBlockBody(optionSet, declaration, forAnalyzer: true); if (canOffer) { // They have an expression body. Create a diagnostic to convert it to a block // if they don't want expression bodies for this member. var location = severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) == ReportDiagnostic.Hidden ? declaration.GetLocation() : helper.GetExpressionBody(declaration).GetLocation(); var properties = ImmutableDictionary<string, string>.Empty; if (fixesError) { properties = properties.Add(FixesError, ""); } var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); return DiagnosticHelper.Create( CreateDescriptorWithId(helper.DiagnosticId, helper.EnforceOnBuild, helper.UseBlockBodyTitle, helper.UseBlockBodyTitle), location, severity, additionalLocations: additionalLocations, properties: properties); } 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.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class UseExpressionBodyDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public const string FixesError = nameof(FixesError); private readonly ImmutableArray<SyntaxKind> _syntaxKinds; private static readonly ImmutableArray<UseExpressionBodyHelper> _helpers = UseExpressionBodyHelper.Helpers; public UseExpressionBodyDiagnosticAnalyzer() : base(GetSupportedDescriptorsWithOptions(), LanguageNames.CSharp) { _syntaxKinds = _helpers.SelectMany(h => h.SyntaxKinds).ToImmutableArray(); } private static ImmutableDictionary<DiagnosticDescriptor, ILanguageSpecificOption> GetSupportedDescriptorsWithOptions() { var builder = ImmutableDictionary.CreateBuilder<DiagnosticDescriptor, ILanguageSpecificOption>(); foreach (var helper in _helpers) { var descriptor = CreateDescriptorWithId(helper.DiagnosticId, helper.EnforceOnBuild, helper.UseExpressionBodyTitle, helper.UseExpressionBodyTitle); builder.Add(descriptor, helper.Option); } return builder.ToImmutable(); } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, _syntaxKinds); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var options = context.Options; var syntaxTree = context.Node.SyntaxTree; var cancellationToken = context.CancellationToken; var optionSet = options.GetAnalyzerOptionSet(syntaxTree, cancellationToken); var nodeKind = context.Node.Kind(); // Don't offer a fix on an accessor, if we would also offer it on the property/indexer. if (UseExpressionBodyForAccessorsHelper.Instance.SyntaxKinds.Contains(nodeKind)) { var grandparent = context.Node.Parent.Parent; if (grandparent.Kind() == SyntaxKind.PropertyDeclaration && AnalyzeSyntax(optionSet, grandparent, UseExpressionBodyForPropertiesHelper.Instance) != null) { return; } if (grandparent.Kind() == SyntaxKind.IndexerDeclaration && AnalyzeSyntax(optionSet, grandparent, UseExpressionBodyForIndexersHelper.Instance) != null) { return; } } foreach (var helper in _helpers) { if (helper.SyntaxKinds.Contains(nodeKind)) { var diagnostic = AnalyzeSyntax(optionSet, context.Node, helper); if (diagnostic != null) { context.ReportDiagnostic(diagnostic); return; } } } } private static Diagnostic AnalyzeSyntax( OptionSet optionSet, SyntaxNode declaration, UseExpressionBodyHelper helper) { var preferExpressionBodiedOption = optionSet.GetOption(helper.Option); var severity = preferExpressionBodiedOption.Notification.Severity; if (helper.CanOfferUseExpressionBody(optionSet, declaration, forAnalyzer: true)) { var location = severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) == ReportDiagnostic.Hidden ? declaration.GetLocation() : helper.GetDiagnosticLocation(declaration); var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); var properties = ImmutableDictionary<string, string>.Empty.Add(nameof(UseExpressionBody), ""); return DiagnosticHelper.Create( CreateDescriptorWithId(helper.DiagnosticId, helper.EnforceOnBuild, helper.UseExpressionBodyTitle, helper.UseExpressionBodyTitle), location, severity, additionalLocations: additionalLocations, properties: properties); } var (canOffer, fixesError) = helper.CanOfferUseBlockBody(optionSet, declaration, forAnalyzer: true); if (canOffer) { // They have an expression body. Create a diagnostic to convert it to a block // if they don't want expression bodies for this member. var location = severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) == ReportDiagnostic.Hidden ? declaration.GetLocation() : helper.GetExpressionBody(declaration).GetLocation(); var properties = ImmutableDictionary<string, string>.Empty; if (fixesError) { properties = properties.Add(FixesError, ""); } var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); return DiagnosticHelper.Create( CreateDescriptorWithId(helper.DiagnosticId, helper.EnforceOnBuild, helper.UseBlockBodyTitle, helper.UseBlockBodyTitle), location, severity, additionalLocations: additionalLocations, properties: properties); } return null; } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Features/Core/Portable/ExternalAccess/VSTypeScript/VSTypeScriptProjectDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [DiagnosticAnalyzer(InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptProjectDiagnosticAnalyzer : ProjectDiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray<DiagnosticDescriptor>.Empty; public override Task<ImmutableArray<Diagnostic>> AnalyzeProjectAsync(Project project, CancellationToken cancellationToken) { var analyzer = project.LanguageServices.GetRequiredService<VSTypeScriptDiagnosticAnalyzerLanguageService>().Implementation; if (analyzer == null) { return SpecializedTasks.EmptyImmutableArray<Diagnostic>(); } return analyzer.AnalyzeProjectAsync(project, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [DiagnosticAnalyzer(InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptProjectDiagnosticAnalyzer : ProjectDiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray<DiagnosticDescriptor>.Empty; public override Task<ImmutableArray<Diagnostic>> AnalyzeProjectAsync(Project project, CancellationToken cancellationToken) { var analyzer = project.LanguageServices.GetRequiredService<VSTypeScriptDiagnosticAnalyzerLanguageService>().Implementation; if (analyzer == null) { return SpecializedTasks.EmptyImmutableArray<Diagnostic>(); } return analyzer.AnalyzeProjectAsync(project, cancellationToken); } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxDiagnosticInfoList.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Syntax.InternalSyntax { // Avoid implementing IEnumerable so we do not get any unintentional boxing. internal struct SyntaxDiagnosticInfoList { private readonly GreenNode _node; internal SyntaxDiagnosticInfoList(GreenNode node) { _node = node; } public Enumerator GetEnumerator() { return new Enumerator(_node); } internal bool Any(Func<DiagnosticInfo, bool> predicate) { var enumerator = GetEnumerator(); while (enumerator.MoveNext()) { if (predicate(enumerator.Current)) return true; } return false; } public struct Enumerator { private struct NodeIteration { internal readonly GreenNode Node; internal int DiagnosticIndex; internal int SlotIndex; internal NodeIteration(GreenNode node) { this.Node = node; this.SlotIndex = -1; this.DiagnosticIndex = -1; } } private NodeIteration[]? _stack; private int _count; public DiagnosticInfo Current { get; private set; } internal Enumerator(GreenNode node) { Current = null!; _stack = null; _count = 0; if (node != null && node.ContainsDiagnostics) { _stack = new NodeIteration[8]; this.PushNodeOrToken(node); } } public bool MoveNext() { while (_count > 0) { var diagIndex = _stack![_count - 1].DiagnosticIndex; var node = _stack[_count - 1].Node; var diags = node.GetDiagnostics(); if (diagIndex < diags.Length - 1) { diagIndex++; Current = diags[diagIndex]; _stack[_count - 1].DiagnosticIndex = diagIndex; return true; } var slotIndex = _stack[_count - 1].SlotIndex; tryAgain: if (slotIndex < node.SlotCount - 1) { slotIndex++; var child = node.GetSlot(slotIndex); if (child == null || !child.ContainsDiagnostics) { goto tryAgain; } _stack[_count - 1].SlotIndex = slotIndex; this.PushNodeOrToken(child); } else { this.Pop(); } } return false; } private void PushNodeOrToken(GreenNode node) { if (node.IsToken) { this.PushToken(node); } else { this.Push(node); } } private void PushToken(GreenNode token) { var trailing = token.GetTrailingTriviaCore(); if (trailing != null) { this.Push(trailing); } this.Push(token); var leading = token.GetLeadingTriviaCore(); if (leading != null) { this.Push(leading); } } private void Push(GreenNode node) { RoslynDebug.Assert(_stack is object); if (_count >= _stack.Length) { var tmp = new NodeIteration[_stack.Length * 2]; Array.Copy(_stack, tmp, _stack.Length); _stack = tmp; } _stack[_count] = new NodeIteration(node); _count++; } private void Pop() { _count--; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Syntax.InternalSyntax { // Avoid implementing IEnumerable so we do not get any unintentional boxing. internal struct SyntaxDiagnosticInfoList { private readonly GreenNode _node; internal SyntaxDiagnosticInfoList(GreenNode node) { _node = node; } public Enumerator GetEnumerator() { return new Enumerator(_node); } internal bool Any(Func<DiagnosticInfo, bool> predicate) { var enumerator = GetEnumerator(); while (enumerator.MoveNext()) { if (predicate(enumerator.Current)) return true; } return false; } public struct Enumerator { private struct NodeIteration { internal readonly GreenNode Node; internal int DiagnosticIndex; internal int SlotIndex; internal NodeIteration(GreenNode node) { this.Node = node; this.SlotIndex = -1; this.DiagnosticIndex = -1; } } private NodeIteration[]? _stack; private int _count; public DiagnosticInfo Current { get; private set; } internal Enumerator(GreenNode node) { Current = null!; _stack = null; _count = 0; if (node != null && node.ContainsDiagnostics) { _stack = new NodeIteration[8]; this.PushNodeOrToken(node); } } public bool MoveNext() { while (_count > 0) { var diagIndex = _stack![_count - 1].DiagnosticIndex; var node = _stack[_count - 1].Node; var diags = node.GetDiagnostics(); if (diagIndex < diags.Length - 1) { diagIndex++; Current = diags[diagIndex]; _stack[_count - 1].DiagnosticIndex = diagIndex; return true; } var slotIndex = _stack[_count - 1].SlotIndex; tryAgain: if (slotIndex < node.SlotCount - 1) { slotIndex++; var child = node.GetSlot(slotIndex); if (child == null || !child.ContainsDiagnostics) { goto tryAgain; } _stack[_count - 1].SlotIndex = slotIndex; this.PushNodeOrToken(child); } else { this.Pop(); } } return false; } private void PushNodeOrToken(GreenNode node) { if (node.IsToken) { this.PushToken(node); } else { this.Push(node); } } private void PushToken(GreenNode token) { var trailing = token.GetTrailingTriviaCore(); if (trailing != null) { this.Push(trailing); } this.Push(token); var leading = token.GetLeadingTriviaCore(); if (leading != null) { this.Push(leading); } } private void Push(GreenNode node) { RoslynDebug.Assert(_stack is object); if (_count >= _stack.Length) { var tmp = new NodeIteration[_stack.Length * 2]; Array.Copy(_stack, tmp, _stack.Length); _stack = tmp; } _stack[_count] = new NodeIteration(node); _count++; } private void Pop() { _count--; } } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Features/Core/Portable/CodeFixes/ICodeFixService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeActions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes { internal interface ICodeFixService { Task<ImmutableArray<CodeFixCollection>> GetFixesAsync(Document document, TextSpan textSpan, bool includeSuppressionFixes, CodeActionRequestPriority priority, bool isBlocking, Func<string, IDisposable?> addOperationScope, CancellationToken cancellationToken); Task<CodeFixCollection?> GetDocumentFixAllForIdInSpanAsync(Document document, TextSpan textSpan, string diagnosticId, CancellationToken cancellationToken); Task<Document> ApplyCodeFixesForSpecificDiagnosticIdAsync(Document document, string diagnosticId, IProgressTracker progressTracker, CancellationToken cancellationToken); CodeFixProvider? GetSuppressionFixer(string language, IEnumerable<string> diagnosticIds); Task<FirstDiagnosticResult> GetMostSevereFixableDiagnosticAsync(Document document, TextSpan range, CancellationToken cancellationToken); } internal static class ICodeFixServiceExtensions { public static Task<ImmutableArray<CodeFixCollection>> GetFixesAsync(this ICodeFixService service, Document document, TextSpan range, bool includeConfigurationFixes, CancellationToken cancellationToken) => service.GetFixesAsync(document, range, includeConfigurationFixes, isBlocking: false, cancellationToken); public static Task<ImmutableArray<CodeFixCollection>> GetFixesAsync(this ICodeFixService service, Document document, TextSpan range, bool includeConfigurationFixes, bool isBlocking, CancellationToken cancellationToken) => service.GetFixesAsync(document, range, includeConfigurationFixes, CodeActionRequestPriority.None, isBlocking, addOperationScope: _ => null, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes { internal interface ICodeFixService { Task<ImmutableArray<CodeFixCollection>> GetFixesAsync(Document document, TextSpan textSpan, bool includeSuppressionFixes, CodeActionRequestPriority priority, bool isBlocking, Func<string, IDisposable?> addOperationScope, CancellationToken cancellationToken); Task<CodeFixCollection?> GetDocumentFixAllForIdInSpanAsync(Document document, TextSpan textSpan, string diagnosticId, CancellationToken cancellationToken); Task<Document> ApplyCodeFixesForSpecificDiagnosticIdAsync(Document document, string diagnosticId, IProgressTracker progressTracker, CancellationToken cancellationToken); CodeFixProvider? GetSuppressionFixer(string language, IEnumerable<string> diagnosticIds); Task<FirstDiagnosticResult> GetMostSevereFixableDiagnosticAsync(Document document, TextSpan range, CancellationToken cancellationToken); } internal static class ICodeFixServiceExtensions { public static Task<ImmutableArray<CodeFixCollection>> GetFixesAsync(this ICodeFixService service, Document document, TextSpan range, bool includeConfigurationFixes, CancellationToken cancellationToken) => service.GetFixesAsync(document, range, includeConfigurationFixes, isBlocking: false, cancellationToken); public static Task<ImmutableArray<CodeFixCollection>> GetFixesAsync(this ICodeFixService service, Document document, TextSpan range, bool includeConfigurationFixes, bool isBlocking, CancellationToken cancellationToken) => service.GetFixesAsync(document, range, includeConfigurationFixes, CodeActionRequestPriority.None, isBlocking, addOperationScope: _ => null, cancellationToken); } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/EditorFeatures/CSharpTest2/Recommendations/StructKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class StructKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonly() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonly() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicRefReadonly() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"public ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonlyRef() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"readonly ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternalReadonlyRef() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"internal readonly ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterReadonlyInMethod() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"class C { void M() { readonly $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefInMethod() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"class C { void M() { ref $$ } }"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRecord() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"record $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstractPublic() => await VerifyAbsenceAsync(@"abstract public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStruct() => await VerifyAbsenceAsync(@"struct $$"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class StructKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonly() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonly() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicRefReadonly() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"public ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonlyRef() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"readonly ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternalReadonlyRef() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"internal readonly ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterReadonlyInMethod() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"class C { void M() { readonly $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefInMethod() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"class C { void M() { ref $$ } }"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRecord() { await VerifyKeywordAsync(SourceCodeKind.Regular, @"record $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstractPublic() => await VerifyAbsenceAsync(@"abstract public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStruct() => await VerifyAbsenceAsync(@"struct $$"); } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/Core/Portable/Symbols/ISymbolExtensions_PerformIVTCheck.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Collections; namespace Microsoft.CodeAnalysis { public static partial class ISymbolExtensions { /// <summary> /// Given that an assembly with identity assemblyGrantingAccessIdentity granted access to assemblyWantingAccess, /// check the public keys to ensure the internals-visible-to check should succeed. This is used by both the /// C# and VB implementations as a helper to implement `bool IAssemblySymbol.GivesAccessTo(IAssemblySymbol toAssembly)`. /// </summary> internal static IVTConclusion PerformIVTCheck( this AssemblyIdentity assemblyGrantingAccessIdentity, ImmutableArray<byte> assemblyWantingAccessKey, ImmutableArray<byte> grantedToPublicKey) { // This gets a bit complicated. Let's break it down. // // First off, let's assume that the "other" assembly is GrantingAssembly.DLL, that the "this" // assembly is "WantingAssembly.DLL", and that GrantingAssembly has named WantingAssembly as a friend (that is a precondition // to calling this method). Whether we allow WantingAssembly to see internals of GrantingAssembly depends on these four factors: // // q1) Is GrantingAssembly strong-named? // q2) Did GrantingAssembly name WantingAssembly as a friend via a strong name? // q3) Is WantingAssembly strong-named? // q4) Does GrantingAssembly give a strong-name for WantingAssembly that matches our strong name? // // Before we dive into the details, we should mention two additional facts: // // * If the answer to q1 is "yes", and GrantingAssembly was compiled by a Roslyn compiler, then q2 must be "yes" also. // Strong-named GrantingAssembly must only be friends with strong-named WantingAssembly. See the blog article // http://blogs.msdn.com/b/ericlippert/archive/2009/06/04/alas-smith-and-jones.aspx // for an explanation of why this feature is desirable. // // Now, just because the compiler enforces this rule does not mean that we will never run into // a scenario where GrantingAssembly is strong-named and names WantingAssembly via a weak name. Not all assemblies // were compiled with a Roslyn compiler. We still need to deal sensibly with this situation. // We do so by ignoring the problem; if strong-named GrantingAssembly extends friendship to weak-named // WantingAssembly then we're done; any assembly named WantingAssembly is a friend of GrantingAssembly. // // Incidentally, the C# compiler produces error CS1726, ERR_FriendAssemblySNReq, and VB produces // the error VB31535, ERR_FriendAssemblyStrongNameRequired, when compiling // a strong-named GrantingAssembly that names a weak-named WantingAssembly as its friend. // // * If the answer to q1 is "no" and the answer to q3 is "yes" then we are in a situation where // strong-named WantingAssembly is referencing weak-named GrantingAssembly, which is illegal. In the dev10 compiler // we do not give an error about this until emit time. In Roslyn we have a new error, CS7029, // which we give before emit time when we detect that weak-named GrantingAssembly has given friend access // to strong-named WantingAssembly, which then references GrantingAssembly. However, we still want to give friend // access to WantingAssembly for the purposes of semantic analysis. // // Roslyn C# does not yet give an error in other circumstances whereby a strong-named assembly // references a weak-named assembly. See https://github.com/dotnet/roslyn/issues/26722 // // Let's make a chart that illustrates all the possible answers to these four questions, and // what the resulting accessibility should be: // // case q1 q2 q3 q4 Result Explanation // 1 YES YES YES YES SUCCESS GrantingAssembly has named this strong-named WantingAssembly as a friend. // 2 YES YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend. // 3 YES YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named. // 4 YES NO YES NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship. // 5 YES NO NO NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship. // 6 NO YES YES YES SUCCESS, BAD REF GrantingAssembly has named this strong-named WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly. // 7 NO YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend. // 8 NO YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named. // 9 NO NO YES NO SUCCESS, BAD REF GrantingAssembly has named any WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly. // 10 NO NO NO NO SUCCESS GrantingAssembly has named any WantingAssembly as its friend. // // (*) GrantingAssembly was not built with a Roslyn compiler, which would have prevented this. // // This method never returns NoRelationshipClaimed because if control got here, then we assume // (as a precondition) that GrantingAssembly named WantingAssembly as a friend somehow. bool q1 = assemblyGrantingAccessIdentity.IsStrongName; bool q2 = !grantedToPublicKey.IsDefaultOrEmpty; bool q3 = !assemblyWantingAccessKey.IsDefaultOrEmpty; bool q4 = (q2 & q3) && ByteSequenceComparer.Equals(grantedToPublicKey, assemblyWantingAccessKey); // Cases 2, 3, 7 and 8: if (q2 && !q4) { return IVTConclusion.PublicKeyDoesntMatch; } // Cases 6 and 9: if (!q1 && q3) { return IVTConclusion.OneSignedOneNot; } // Cases 1, 4, 5 and 10: return IVTConclusion.Match; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Collections; namespace Microsoft.CodeAnalysis { public static partial class ISymbolExtensions { /// <summary> /// Given that an assembly with identity assemblyGrantingAccessIdentity granted access to assemblyWantingAccess, /// check the public keys to ensure the internals-visible-to check should succeed. This is used by both the /// C# and VB implementations as a helper to implement `bool IAssemblySymbol.GivesAccessTo(IAssemblySymbol toAssembly)`. /// </summary> internal static IVTConclusion PerformIVTCheck( this AssemblyIdentity assemblyGrantingAccessIdentity, ImmutableArray<byte> assemblyWantingAccessKey, ImmutableArray<byte> grantedToPublicKey) { // This gets a bit complicated. Let's break it down. // // First off, let's assume that the "other" assembly is GrantingAssembly.DLL, that the "this" // assembly is "WantingAssembly.DLL", and that GrantingAssembly has named WantingAssembly as a friend (that is a precondition // to calling this method). Whether we allow WantingAssembly to see internals of GrantingAssembly depends on these four factors: // // q1) Is GrantingAssembly strong-named? // q2) Did GrantingAssembly name WantingAssembly as a friend via a strong name? // q3) Is WantingAssembly strong-named? // q4) Does GrantingAssembly give a strong-name for WantingAssembly that matches our strong name? // // Before we dive into the details, we should mention two additional facts: // // * If the answer to q1 is "yes", and GrantingAssembly was compiled by a Roslyn compiler, then q2 must be "yes" also. // Strong-named GrantingAssembly must only be friends with strong-named WantingAssembly. See the blog article // http://blogs.msdn.com/b/ericlippert/archive/2009/06/04/alas-smith-and-jones.aspx // for an explanation of why this feature is desirable. // // Now, just because the compiler enforces this rule does not mean that we will never run into // a scenario where GrantingAssembly is strong-named and names WantingAssembly via a weak name. Not all assemblies // were compiled with a Roslyn compiler. We still need to deal sensibly with this situation. // We do so by ignoring the problem; if strong-named GrantingAssembly extends friendship to weak-named // WantingAssembly then we're done; any assembly named WantingAssembly is a friend of GrantingAssembly. // // Incidentally, the C# compiler produces error CS1726, ERR_FriendAssemblySNReq, and VB produces // the error VB31535, ERR_FriendAssemblyStrongNameRequired, when compiling // a strong-named GrantingAssembly that names a weak-named WantingAssembly as its friend. // // * If the answer to q1 is "no" and the answer to q3 is "yes" then we are in a situation where // strong-named WantingAssembly is referencing weak-named GrantingAssembly, which is illegal. In the dev10 compiler // we do not give an error about this until emit time. In Roslyn we have a new error, CS7029, // which we give before emit time when we detect that weak-named GrantingAssembly has given friend access // to strong-named WantingAssembly, which then references GrantingAssembly. However, we still want to give friend // access to WantingAssembly for the purposes of semantic analysis. // // Roslyn C# does not yet give an error in other circumstances whereby a strong-named assembly // references a weak-named assembly. See https://github.com/dotnet/roslyn/issues/26722 // // Let's make a chart that illustrates all the possible answers to these four questions, and // what the resulting accessibility should be: // // case q1 q2 q3 q4 Result Explanation // 1 YES YES YES YES SUCCESS GrantingAssembly has named this strong-named WantingAssembly as a friend. // 2 YES YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend. // 3 YES YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named. // 4 YES NO YES NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship. // 5 YES NO NO NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship. // 6 NO YES YES YES SUCCESS, BAD REF GrantingAssembly has named this strong-named WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly. // 7 NO YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend. // 8 NO YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named. // 9 NO NO YES NO SUCCESS, BAD REF GrantingAssembly has named any WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly. // 10 NO NO NO NO SUCCESS GrantingAssembly has named any WantingAssembly as its friend. // // (*) GrantingAssembly was not built with a Roslyn compiler, which would have prevented this. // // This method never returns NoRelationshipClaimed because if control got here, then we assume // (as a precondition) that GrantingAssembly named WantingAssembly as a friend somehow. bool q1 = assemblyGrantingAccessIdentity.IsStrongName; bool q2 = !grantedToPublicKey.IsDefaultOrEmpty; bool q3 = !assemblyWantingAccessKey.IsDefaultOrEmpty; bool q4 = (q2 & q3) && ByteSequenceComparer.Equals(grantedToPublicKey, assemblyWantingAccessKey); // Cases 2, 3, 7 and 8: if (q2 && !q4) { return IVTConclusion.PublicKeyDoesntMatch; } // Cases 6 and 9: if (!q1 && q3) { return IVTConclusion.OneSignedOneNot; } // Cases 1, 4, 5 and 10: return IVTConclusion.Match; } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/EditorFeatures/CSharpTest/Structure/DocumentationCommentStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class DocumentationCommentStructureTests : AbstractCSharpSyntaxNodeStructureTests<DocumentationCommentTriviaSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new DocumentationCommentStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag1() { const string code = @" {|span:/// $$XML doc comment /// some description /// of /// the comment|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// XML doc comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag2() { const string code = @" {|span:/** $$Block comment * some description * of * the comment */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** Block comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag3() { const string code = @" {|span:/// $$<param name=""tree""></param>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <param name=\"tree\"></param> ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithLongBannerText() { var code = @" {|span:/// $$<summary> /// " + new string('x', 240) + @" /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> " + new string('x', 106) + " ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment1() { const string code = @" {|span:/// <summary> /// $$Hello /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment2() { const string code = @" {|span:/// <summary> /// $$Hello /// /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] [WorkItem(2129, "https://github.com/dotnet/roslyn/issues/2129")] public async Task CrefInSummary() { const string code = @" class C { {|span:/// $$<summary> /// Summary with <see cref=""SeeClass"" />, <seealso cref=""SeeAlsoClass"" />, /// <see langword=""null"" />, <typeparamref name=""T"" />, <paramref name=""t"" />, and <see unsupported-attribute=""not-supported"" />. /// </summary>|} public void M<T>(T t) { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Summary with SeeClass, SeeAlsoClass, null, T, t, and not-supported.", autoCollapse: true)); } [WorkItem(402822, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=402822")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithPunctuation() { const string code = @" class C { {|span:/// $$<summary> /// The main entrypoint for <see cref=""Program""/>. /// </summary> /// <param name=""args""></param>|} void Main() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> The main entrypoint for Program.", autoCollapse: true)); } [WorkItem(20679, "https://github.com/dotnet/roslyn/issues/20679")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithAdditionalTags() { const string code = @" public class Class1 { {|span:/// $$<summary> /// Initializes a <c>new</c> instance of the <see cref=""Class1"" /> class. /// </summary>|} public Class1() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Initializes a new instance of the Class1 class.", autoCollapse: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class DocumentationCommentStructureTests : AbstractCSharpSyntaxNodeStructureTests<DocumentationCommentTriviaSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new DocumentationCommentStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag1() { const string code = @" {|span:/// $$XML doc comment /// some description /// of /// the comment|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// XML doc comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag2() { const string code = @" {|span:/** $$Block comment * some description * of * the comment */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** Block comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag3() { const string code = @" {|span:/// $$<param name=""tree""></param>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <param name=\"tree\"></param> ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithLongBannerText() { var code = @" {|span:/// $$<summary> /// " + new string('x', 240) + @" /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> " + new string('x', 106) + " ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment1() { const string code = @" {|span:/// <summary> /// $$Hello /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment2() { const string code = @" {|span:/// <summary> /// $$Hello /// /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] [WorkItem(2129, "https://github.com/dotnet/roslyn/issues/2129")] public async Task CrefInSummary() { const string code = @" class C { {|span:/// $$<summary> /// Summary with <see cref=""SeeClass"" />, <seealso cref=""SeeAlsoClass"" />, /// <see langword=""null"" />, <typeparamref name=""T"" />, <paramref name=""t"" />, and <see unsupported-attribute=""not-supported"" />. /// </summary>|} public void M<T>(T t) { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Summary with SeeClass, SeeAlsoClass, null, T, t, and not-supported.", autoCollapse: true)); } [WorkItem(402822, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=402822")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithPunctuation() { const string code = @" class C { {|span:/// $$<summary> /// The main entrypoint for <see cref=""Program""/>. /// </summary> /// <param name=""args""></param>|} void Main() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> The main entrypoint for Program.", autoCollapse: true)); } [WorkItem(20679, "https://github.com/dotnet/roslyn/issues/20679")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithAdditionalTags() { const string code = @" public class Class1 { {|span:/// $$<summary> /// Initializes a <c>new</c> instance of the <see cref=""Class1"" /> class. /// </summary>|} public Class1() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Initializes a new instance of the Class1 class.", autoCollapse: true)); } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/StartPage_OutOfProc.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class StartPage_OutOfProc : OutOfProcComponent { private readonly StartPage_InProc _inProc; public StartPage_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<StartPage_InProc>(visualStudioInstance); } public bool IsEnabled() => _inProc.IsEnabled(); public void SetEnabled(bool enabled) => _inProc.SetEnabled(enabled); public bool CloseWindow() => _inProc.CloseWindow(); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class StartPage_OutOfProc : OutOfProcComponent { private readonly StartPage_InProc _inProc; public StartPage_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<StartPage_InProc>(visualStudioInstance); } public bool IsEnabled() => _inProc.IsEnabled(); public void SetEnabled(bool enabled) => _inProc.SetEnabled(enabled); public bool CloseWindow() => _inProc.CloseWindow(); } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsClassificationTaggerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { [Export(typeof(ITaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TagType(typeof(ClassificationTag))] internal partial class DiagnosticsClassificationTaggerProvider : AbstractDiagnosticsTaggerProvider<ClassificationTag> { private static readonly IEnumerable<Option2<bool>> s_tagSourceOptions = new[] { EditorComponentOnOffOptions.Tagger, InternalFeatureOnOffOptions.Classification, ServiceComponentOnOffOptions.DiagnosticProvider }; private readonly ClassificationTypeMap _typeMap; private readonly ClassificationTag _classificationTag; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; protected override IEnumerable<Option2<bool>> Options => s_tagSourceOptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DiagnosticsClassificationTaggerProvider( IThreadingContext threadingContext, IDiagnosticService diagnosticService, ClassificationTypeMap typeMap, IEditorOptionsFactoryService editorOptionsFactoryService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, diagnosticService, listenerProvider.GetListener(FeatureAttribute.Classification)) { _typeMap = typeMap; _classificationTag = new ClassificationTag(_typeMap.GetClassificationType(ClassificationTypeDefinitions.UnnecessaryCode)); _editorOptionsFactoryService = editorOptionsFactoryService; } // If we are under high contrast mode, the editor ignores classification tags that fade things out, // because that reduces contrast. Since the editor will ignore them, there's no reason to produce them. protected internal override bool IsEnabled => !_editorOptionsFactoryService.GlobalOptions.GetOptionValue(DefaultTextViewHostOptions.IsInContrastModeId); protected internal override bool IncludeDiagnostic(DiagnosticData data) => data.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary); protected internal override ITagSpan<ClassificationTag> CreateTagSpan(Workspace workspace, bool isLiveUpdate, SnapshotSpan span, DiagnosticData data) => new TagSpan<ClassificationTag>(span, _classificationTag); protected internal override ImmutableArray<DiagnosticDataLocation> GetLocationsToTag(DiagnosticData diagnosticData) { // If there are 'unnecessary' locations specified in the property bag, use those instead of the main diagnostic location. if (diagnosticData.AdditionalLocations.Length > 0 && diagnosticData.Properties != null && diagnosticData.Properties.TryGetValue(WellKnownDiagnosticTags.Unnecessary, out var unnecessaryIndices) && unnecessaryIndices is object) { using var _ = PooledObjects.ArrayBuilder<DiagnosticDataLocation>.GetInstance(out var locationsToTag); foreach (var index in GetLocationIndices(unnecessaryIndices)) locationsToTag.Add(diagnosticData.AdditionalLocations[index]); return locationsToTag.ToImmutable(); } // Default to the base implementation for the diagnostic data return base.GetLocationsToTag(diagnosticData); static IEnumerable<int> GetLocationIndices(string indicesProperty) { try { using var stream = new MemoryStream(Encoding.UTF8.GetBytes(indicesProperty)); var serializer = new DataContractJsonSerializer(typeof(IEnumerable<int>)); var result = serializer.ReadObject(stream) as IEnumerable<int>; return result ?? Array.Empty<int>(); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { return ImmutableArray<int>.Empty; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { [Export(typeof(ITaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TagType(typeof(ClassificationTag))] internal partial class DiagnosticsClassificationTaggerProvider : AbstractDiagnosticsTaggerProvider<ClassificationTag> { private static readonly IEnumerable<Option2<bool>> s_tagSourceOptions = new[] { EditorComponentOnOffOptions.Tagger, InternalFeatureOnOffOptions.Classification, ServiceComponentOnOffOptions.DiagnosticProvider }; private readonly ClassificationTypeMap _typeMap; private readonly ClassificationTag _classificationTag; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; protected override IEnumerable<Option2<bool>> Options => s_tagSourceOptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DiagnosticsClassificationTaggerProvider( IThreadingContext threadingContext, IDiagnosticService diagnosticService, ClassificationTypeMap typeMap, IEditorOptionsFactoryService editorOptionsFactoryService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, diagnosticService, listenerProvider.GetListener(FeatureAttribute.Classification)) { _typeMap = typeMap; _classificationTag = new ClassificationTag(_typeMap.GetClassificationType(ClassificationTypeDefinitions.UnnecessaryCode)); _editorOptionsFactoryService = editorOptionsFactoryService; } // If we are under high contrast mode, the editor ignores classification tags that fade things out, // because that reduces contrast. Since the editor will ignore them, there's no reason to produce them. protected internal override bool IsEnabled => !_editorOptionsFactoryService.GlobalOptions.GetOptionValue(DefaultTextViewHostOptions.IsInContrastModeId); protected internal override bool IncludeDiagnostic(DiagnosticData data) => data.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary); protected internal override ITagSpan<ClassificationTag> CreateTagSpan(Workspace workspace, bool isLiveUpdate, SnapshotSpan span, DiagnosticData data) => new TagSpan<ClassificationTag>(span, _classificationTag); protected internal override ImmutableArray<DiagnosticDataLocation> GetLocationsToTag(DiagnosticData diagnosticData) { // If there are 'unnecessary' locations specified in the property bag, use those instead of the main diagnostic location. if (diagnosticData.AdditionalLocations.Length > 0 && diagnosticData.Properties != null && diagnosticData.Properties.TryGetValue(WellKnownDiagnosticTags.Unnecessary, out var unnecessaryIndices) && unnecessaryIndices is object) { using var _ = PooledObjects.ArrayBuilder<DiagnosticDataLocation>.GetInstance(out var locationsToTag); foreach (var index in GetLocationIndices(unnecessaryIndices)) locationsToTag.Add(diagnosticData.AdditionalLocations[index]); return locationsToTag.ToImmutable(); } // Default to the base implementation for the diagnostic data return base.GetLocationsToTag(diagnosticData); static IEnumerable<int> GetLocationIndices(string indicesProperty) { try { using var stream = new MemoryStream(Encoding.UTF8.GetBytes(indicesProperty)); var serializer = new DataContractJsonSerializer(typeof(IEnumerable<int>)); var result = serializer.ReadObject(stream) as IEnumerable<int>; return result ?? Array.Empty<int>(); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { return ImmutableArray<int>.Empty; } } } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/CSharp/Portable/Binder/Binder_Crefs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { internal ImmutableArray<Symbol> BindCref(CrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { ImmutableArray<Symbol> symbols = BindCrefInternal(syntax, out ambiguityWinner, diagnostics); Debug.Assert(!symbols.IsDefault, "Prefer empty to null."); Debug.Assert((symbols.Length > 1) == ((object?)ambiguityWinner != null), "ambiguityWinner should be set iff more than one symbol is returned."); return symbols; } private ImmutableArray<Symbol> BindCrefInternal(CrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { switch (syntax.Kind()) { case SyntaxKind.TypeCref: return BindTypeCref((TypeCrefSyntax)syntax, out ambiguityWinner, diagnostics); case SyntaxKind.QualifiedCref: return BindQualifiedCref((QualifiedCrefSyntax)syntax, out ambiguityWinner, diagnostics); case SyntaxKind.NameMemberCref: case SyntaxKind.IndexerMemberCref: case SyntaxKind.OperatorMemberCref: case SyntaxKind.ConversionOperatorMemberCref: return BindMemberCref((MemberCrefSyntax)syntax, containerOpt: null, ambiguityWinner: out ambiguityWinner, diagnostics: diagnostics); default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } private ImmutableArray<Symbol> BindTypeCref(TypeCrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { NamespaceOrTypeSymbol result = BindNamespaceOrTypeSymbolInCref(syntax.Type); // NOTE: we don't have to worry about the case where a non-error type is constructed // with erroneous type arguments, because only MemberCrefs have type arguments - // all other crefs only have type parameters. if (result.Kind == SymbolKind.ErrorType) { var noTrivia = syntax.WithLeadingTrivia(null).WithTrailingTrivia(null); diagnostics.Add(ErrorCode.WRN_BadXMLRef, syntax.Location, noTrivia.ToFullString()); } // We'll never have more than one type, but it is conceivable that result could // be an ExtendedErrorTypeSymbol with multiple candidates. ambiguityWinner = null; return ImmutableArray.Create<Symbol>(result); } private ImmutableArray<Symbol> BindQualifiedCref(QualifiedCrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { // NOTE: we won't check whether container is an error type - we'll just let BindMemberCref fail // and report a blanket diagnostic. NamespaceOrTypeSymbol container = BindNamespaceOrTypeSymbolInCref(syntax.Container); return BindMemberCref(syntax.Member, container, out ambiguityWinner, diagnostics); } /// <summary> /// We can't use BindNamespaceOrTypeSymbol, since it doesn't return inaccessible symbols (directly). /// </summary> /// <remarks> /// Guaranteed not to return null. /// /// CONSIDER: As in dev11, we don't handle ambiguity at this level. Hypothetically, /// we could just pick one, though an "ideal" solution would probably involve a search /// down all ambiguous branches. /// </remarks> private NamespaceOrTypeSymbol BindNamespaceOrTypeSymbolInCref(TypeSyntax syntax) { Debug.Assert(Flags.Includes(BinderFlags.Cref)); // BREAK: Dev11 used to do a second lookup, ignoring accessibility, if the first lookup failed. // VS BUG#3321137: we need to try to find accessible members first // especially for compiler generated events (the backing field is private // but has the same name as the public event, and there is no easy way to // set the isEvent field on imported MEMBVARSYMs) // Diagnostics that don't prevent us from getting a symbol don't matter - the caller will report // an umbrella diagnostic if the result is an error type. NamespaceOrTypeSymbol namespaceOrTypeSymbol = BindNamespaceOrTypeSymbol(syntax, BindingDiagnosticBag.Discarded).NamespaceOrTypeSymbol; Debug.Assert((object)namespaceOrTypeSymbol != null); return namespaceOrTypeSymbol; } private ImmutableArray<Symbol> BindMemberCref(MemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { if ((object?)containerOpt != null && containerOpt.Kind == SymbolKind.TypeParameter) { // As in normal lookup (see CreateErrorIfLookupOnTypeParameter), you can't dot into a type parameter // (though you can dot into an expression of type parameter type). CrefSyntax crefSyntax = GetRootCrefSyntax(syntax); var noTrivia = syntax.WithLeadingTrivia(null).WithTrailingTrivia(null); diagnostics.Add(ErrorCode.WRN_BadXMLRef, crefSyntax.Location, noTrivia.ToFullString()); ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } ImmutableArray<Symbol> result; switch (syntax.Kind()) { case SyntaxKind.NameMemberCref: result = BindNameMemberCref((NameMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics); break; case SyntaxKind.IndexerMemberCref: result = BindIndexerMemberCref((IndexerMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics); break; case SyntaxKind.OperatorMemberCref: result = BindOperatorMemberCref((OperatorMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics); break; case SyntaxKind.ConversionOperatorMemberCref: result = BindConversionOperatorMemberCref((ConversionOperatorMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } if (!result.Any()) { CrefSyntax crefSyntax = GetRootCrefSyntax(syntax); var noTrivia = syntax.WithLeadingTrivia(null).WithTrailingTrivia(null); diagnostics.Add(ErrorCode.WRN_BadXMLRef, crefSyntax.Location, noTrivia.ToFullString()); } return result; } private ImmutableArray<Symbol> BindNameMemberCref(NameMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { SimpleNameSyntax? nameSyntax = syntax.Name as SimpleNameSyntax; int arity; string memberName; if (nameSyntax != null) { arity = nameSyntax.Arity; memberName = nameSyntax.Identifier.ValueText; } else { // If the name isn't a SimpleNameSyntax, then we must have a type name followed by a parameter list. // Thus, we're looking for a constructor. Debug.Assert((object?)containerOpt == null); // Could be an error type, but we'll just lookup fail below. containerOpt = BindNamespaceOrTypeSymbolInCref(syntax.Name); arity = 0; memberName = WellKnownMemberNames.InstanceConstructorName; } if (string.IsNullOrEmpty(memberName)) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } ImmutableArray<Symbol> sortedSymbols = ComputeSortedCrefMembers(syntax, containerOpt, memberName, arity, syntax.Parameters != null, diagnostics); if (sortedSymbols.IsEmpty) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } return ProcessCrefMemberLookupResults( sortedSymbols, arity, syntax, typeArgumentListSyntax: arity == 0 ? null : ((GenericNameSyntax)nameSyntax!).TypeArgumentList, parameterListSyntax: syntax.Parameters, ambiguityWinner: out ambiguityWinner, diagnostics: diagnostics); } private ImmutableArray<Symbol> BindIndexerMemberCref(IndexerMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { const int arity = 0; ImmutableArray<Symbol> sortedSymbols = ComputeSortedCrefMembers(syntax, containerOpt, WellKnownMemberNames.Indexer, arity, syntax.Parameters != null, diagnostics); if (sortedSymbols.IsEmpty) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } // Since only indexers are named WellKnownMemberNames.Indexer. Debug.Assert(sortedSymbols.All(SymbolExtensions.IsIndexer)); // NOTE: guaranteed to be a property, because only indexers are considered. return ProcessCrefMemberLookupResults( sortedSymbols, arity, syntax, typeArgumentListSyntax: null, parameterListSyntax: syntax.Parameters, ambiguityWinner: out ambiguityWinner, diagnostics: diagnostics); } // NOTE: not guaranteed to be a method (e.g. class op_Addition) // NOTE: constructor fallback logic applies private ImmutableArray<Symbol> BindOperatorMemberCref(OperatorMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { const int arity = 0; CrefParameterListSyntax? parameterListSyntax = syntax.Parameters; // NOTE: Prefer binary to unary, unless there is exactly one parameter. // CONSIDER: we're following dev11 by never using a binary operator name if there's // exactly one parameter, but doing so would allow us to match single-parameter constructors. SyntaxKind operatorTokenKind = syntax.OperatorToken.Kind(); string? memberName = parameterListSyntax != null && parameterListSyntax.Parameters.Count == 1 ? null : OperatorFacts.BinaryOperatorNameFromSyntaxKindIfAny(operatorTokenKind); memberName = memberName ?? OperatorFacts.UnaryOperatorNameFromSyntaxKindIfAny(operatorTokenKind); if (memberName == null) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } ImmutableArray<Symbol> sortedSymbols = ComputeSortedCrefMembers(syntax, containerOpt, memberName, arity, syntax.Parameters != null, diagnostics); if (sortedSymbols.IsEmpty) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } return ProcessCrefMemberLookupResults( sortedSymbols, arity, syntax, typeArgumentListSyntax: null, parameterListSyntax: parameterListSyntax, ambiguityWinner: out ambiguityWinner, diagnostics: diagnostics); } // NOTE: not guaranteed to be a method (e.g. class op_Implicit) private ImmutableArray<Symbol> BindConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { const int arity = 0; string memberName = syntax.ImplicitOrExplicitKeyword.Kind() == SyntaxKind.ImplicitKeyword ? WellKnownMemberNames.ImplicitConversionName : WellKnownMemberNames.ExplicitConversionName; ImmutableArray<Symbol> sortedSymbols = ComputeSortedCrefMembers(syntax, containerOpt, memberName, arity, syntax.Parameters != null, diagnostics); if (sortedSymbols.IsEmpty) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } TypeSymbol returnType = BindCrefParameterOrReturnType(syntax.Type, syntax, diagnostics); // Filter out methods with the wrong return type, since overload resolution won't catch these. sortedSymbols = sortedSymbols.WhereAsArray((symbol, returnType) => symbol.Kind != SymbolKind.Method || TypeSymbol.Equals(((MethodSymbol)symbol).ReturnType, returnType, TypeCompareKind.ConsiderEverything2), returnType); if (!sortedSymbols.Any()) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } return ProcessCrefMemberLookupResults( sortedSymbols, arity, syntax, typeArgumentListSyntax: null, parameterListSyntax: syntax.Parameters, ambiguityWinner: out ambiguityWinner, diagnostics: diagnostics); } /// <summary> /// Perform lookup (optionally, in a specified container). If nothing is found and the member name matches the containing type /// name, then use the instance constructors of the type instead. The resulting symbols are sorted since tie-breaking is based /// on order and we want cref binding to be repeatable. /// </summary> /// <remarks> /// Never returns null. /// </remarks> private ImmutableArray<Symbol> ComputeSortedCrefMembers(CSharpSyntaxNode syntax, NamespaceOrTypeSymbol? containerOpt, string memberName, int arity, bool hasParameterList, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var result = ComputeSortedCrefMembers(containerOpt, memberName, arity, hasParameterList, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return result; } private ImmutableArray<Symbol> ComputeSortedCrefMembers(NamespaceOrTypeSymbol? containerOpt, string memberName, int arity, bool hasParameterList, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Since we may find symbols without going through the lookup API, // expose the symbols via an ArrayBuilder. ArrayBuilder<Symbol> builder; { LookupResult result = LookupResult.GetInstance(); this.LookupSymbolsOrMembersInternal( result, containerOpt, name: memberName, arity: arity, basesBeingResolved: null, options: LookupOptions.AllMethodsOnArityZero, diagnose: false, useSiteInfo: ref useSiteInfo); // CONSIDER: Dev11 also checks for a constructor in the event of an ambiguous result. if (result.IsMultiViable) { // Dev11 doesn't consider members from System.Object when the container is an interface. // Lookup should already have dropped such members. builder = ArrayBuilder<Symbol>.GetInstance(); builder.AddRange(result.Symbols); result.Free(); } else { result.Free(); // Won't be using this. // Dev11 has a complicated two-stage process for determining when a cref is really referring to a constructor. // Under two sets of conditions, XmlDocCommentBinder::bindXMLReferenceName will decide that a name refers // to a constructor and under one set of conditions, the calling method, XmlDocCommentBinder::bindXMLReference, // will roll back that decision and return null. // In XmlDocCommentBinder::bindXMLReferenceName: // 1) If an unqualified, non-generic name didn't bind to anything and the name matches the name of the type // to which the doc comment is applied, then bind to a constructor. // 2) If a qualified, non-generic name didn't bind to anything and the LHS of the qualified name is a type // with the same name, then bind to a constructor. // Quoted from XmlDocCommentBinder::bindXMLReference: // Filtering out the case where specifying the name of a generic type without specifying // any arity returns a constructor. This case shouldn't return anything. Note that // returning the constructors was a fix for the wonky constructor behavior, but in order // to not introduce a regression and breaking change we return NULL in this case. // e.g. // // /// <see cref="Goo"/> // class Goo<T> { } // // This cref used not to bind to anything, because before it was looking for a type and // since there was no arity, it didn't find Goo<T>. Now however, it finds Goo<T>.ctor, // which is arguably correct, but would be a breaking change (albeit with minimal impact) // so we catch this case and chuck out the symbol found. // In Roslyn, we're doing everything in one pass, rather than guessing and rolling back. // As in the native compiler, we treat this as a fallback case - something that actually has the // specified name is preferred. NamedTypeSymbol? constructorType = null; if (arity == 0) // Member arity { NamedTypeSymbol? containerType = containerOpt as NamedTypeSymbol; if ((object?)containerType != null) { // Case 1: If the name is qualified by a type with the same name, then we want a // constructor (unless the type is generic, the cref is on/in the type (but not // on/in a nested type), and there were no parens after the member name). if (containerType.Name == memberName && (hasParameterList || containerType.Arity == 0 || !TypeSymbol.Equals(this.ContainingType, containerType.OriginalDefinition, TypeCompareKind.ConsiderEverything2))) { constructorType = containerType; } } else if ((object?)containerOpt == null && hasParameterList) { // Case 2: If the name is not qualified by anything, but we're in the scope // of a type with the same name (regardless of arity), then we want a constructor, // as long as there were parens after the member name. NamedTypeSymbol? binderContainingType = this.ContainingType; if ((object?)binderContainingType != null && memberName == binderContainingType.Name) { constructorType = binderContainingType; } } } if ((object?)constructorType != null) { ImmutableArray<MethodSymbol> instanceConstructors = constructorType.InstanceConstructors; int numInstanceConstructors = instanceConstructors.Length; if (numInstanceConstructors == 0) { return ImmutableArray<Symbol>.Empty; } builder = ArrayBuilder<Symbol>.GetInstance(numInstanceConstructors); builder.AddRange(instanceConstructors); } else { return ImmutableArray<Symbol>.Empty; } } } Debug.Assert(builder != null); // Since we resolve ambiguities by just picking the first symbol we encounter, // the order of the symbols matters for repeatability. if (builder.Count > 1) { builder.Sort(ConsistentSymbolOrder.Instance); } return builder.ToImmutableAndFree(); } /// <summary> /// Given a list of viable lookup results (based on the name, arity, and containing symbol), /// attempt to select one. /// </summary> private ImmutableArray<Symbol> ProcessCrefMemberLookupResults( ImmutableArray<Symbol> symbols, int arity, MemberCrefSyntax memberSyntax, TypeArgumentListSyntax? typeArgumentListSyntax, BaseCrefParameterListSyntax? parameterListSyntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { Debug.Assert(!symbols.IsEmpty); if (parameterListSyntax == null) { return ProcessParameterlessCrefMemberLookupResults(symbols, arity, memberSyntax, typeArgumentListSyntax, out ambiguityWinner, diagnostics); } ArrayBuilder<Symbol> candidates = ArrayBuilder<Symbol>.GetInstance(); GetCrefOverloadResolutionCandidates(symbols, arity, typeArgumentListSyntax, candidates); ImmutableArray<ParameterSymbol> parameterSymbols = BindCrefParameters(parameterListSyntax, diagnostics); ImmutableArray<Symbol> results = PerformCrefOverloadResolution(candidates, parameterSymbols, arity, memberSyntax, out ambiguityWinner, diagnostics); candidates.Free(); // NOTE: This diagnostic is just a hint that might help fix a broken cref, so don't do // any work unless there are no viable candidates. if (results.Length == 0) { for (int i = 0; i < parameterSymbols.Length; i++) { if (ContainsNestedTypeOfUnconstructedGenericType(parameterSymbols[i].Type)) { // This warning is new in Roslyn, because our better-defined semantics for // cref lookup disallow some things that were possible in dev12. // // Consider the following code: // // public class C<T> // { // public class Inner { } // // public void M(Inner i) { } // // /// <see cref="M"/> // /// <see cref="C{T}.M"/> // /// <see cref="C{Q}.M"/> // /// <see cref="C{Q}.M(C{Q}.Inner)"/> // /// <see cref="C{Q}.M(Inner)"/> // WRN_UnqualifiedNestedTypeInCref // public void N() { } // } // // Dev12 binds all of the crefs as "M:C`1.M(C{`0}.Inner)". // Roslyn accepts all but the last. The issue is that the context for performing // the lookup is not C<Q>, but C<T>. Consequently, Inner binds to C<T>.Inner and // then overload resolution fails because C<T>.Inner does not match C<Q>.Inner, // the parameter type of C<Q>.M. Since we could not agree that the old behavior // was desirable (other than for backwards compatibility) and since mimicking it // would have been expensive, we settled on introducing a new warning that at // least hints to the user how then can work around the issue (i.e. by qualifying // Inner as C{Q}.Inner). Additional details are available in DevDiv #743425. // // CONSIDER: We could actually put the qualified form in the warning message, // but that would probably just make it more frustrating (i.e. if the compiler // knows exactly what I mean, why do I have to type it). // // NOTE: This is not a great location (whole parameter instead of problematic type), // but it's better than nothing. diagnostics.Add(ErrorCode.WRN_UnqualifiedNestedTypeInCref, parameterListSyntax.Parameters[i].Location); break; } } } return results; } private static bool ContainsNestedTypeOfUnconstructedGenericType(TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Array: return ContainsNestedTypeOfUnconstructedGenericType(((ArrayTypeSymbol)type).ElementType); case TypeKind.Pointer: return ContainsNestedTypeOfUnconstructedGenericType(((PointerTypeSymbol)type).PointedAtType); case TypeKind.FunctionPointer: MethodSymbol signature = ((FunctionPointerTypeSymbol)type).Signature; if (ContainsNestedTypeOfUnconstructedGenericType(signature.ReturnType)) { return true; } foreach (var param in signature.Parameters) { if (ContainsNestedTypeOfUnconstructedGenericType(param.Type)) { return true; } } return false; case TypeKind.Delegate: case TypeKind.Class: case TypeKind.Interface: case TypeKind.Struct: case TypeKind.Enum: case TypeKind.Error: NamedTypeSymbol namedType = (NamedTypeSymbol)type; if (IsNestedTypeOfUnconstructedGenericType(namedType)) { return true; } foreach (TypeWithAnnotations typeArgument in namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { if (ContainsNestedTypeOfUnconstructedGenericType(typeArgument.Type)) { return true; } } return false; case TypeKind.Dynamic: case TypeKind.TypeParameter: return false; default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private static bool IsNestedTypeOfUnconstructedGenericType(NamedTypeSymbol type) { NamedTypeSymbol containing = type.ContainingType; while ((object)containing != null) { if (containing.Arity > 0 && containing.IsDefinition) { return true; } containing = containing.ContainingType; } return false; } /// <summary> /// At this point, we have a list of viable symbols and no parameter list with which to perform /// overload resolution. We'll just return the first symbol, giving a diagnostic if there are /// others. /// Caveat: If there are multiple candidates and only one is from source, then the source symbol /// wins and no diagnostic is reported. /// </summary> private ImmutableArray<Symbol> ProcessParameterlessCrefMemberLookupResults( ImmutableArray<Symbol> symbols, int arity, MemberCrefSyntax memberSyntax, TypeArgumentListSyntax? typeArgumentListSyntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { // If the syntax indicates arity zero, then we match methods of any arity. // However, if there are both generic and non-generic methods, then the // generic methods should be ignored. if (symbols.Length > 1 && arity == 0) { bool hasNonGenericMethod = false; bool hasGenericMethod = false; foreach (Symbol s in symbols) { if (s.Kind != SymbolKind.Method) { continue; } if (((MethodSymbol)s).Arity == 0) { hasNonGenericMethod = true; } else { hasGenericMethod = true; } if (hasGenericMethod && hasNonGenericMethod) { break; //Nothing else to be learned. } } if (hasNonGenericMethod && hasGenericMethod) { symbols = symbols.WhereAsArray(s => s.Kind != SymbolKind.Method || ((MethodSymbol)s).Arity == 0); } } Debug.Assert(!symbols.IsEmpty); Symbol symbol = symbols[0]; // If there's ambiguity, prefer source symbols. // Logic is similar to ResultSymbol, but separate because the error handling is totally different. if (symbols.Length > 1) { // Size is known, but IndexOfSymbolFromCurrentCompilation expects a builder. ArrayBuilder<Symbol> unwrappedSymbols = ArrayBuilder<Symbol>.GetInstance(symbols.Length); foreach (Symbol wrapped in symbols) { unwrappedSymbols.Add(UnwrapAliasNoDiagnostics(wrapped)); } BestSymbolInfo secondBest; BestSymbolInfo best = GetBestSymbolInfo(unwrappedSymbols, out secondBest); Debug.Assert(!best.IsNone); Debug.Assert(!secondBest.IsNone); unwrappedSymbols.Free(); int symbolIndex = 0; if (best.IsFromCompilation) { symbolIndex = best.Index; symbol = symbols[symbolIndex]; // NOTE: symbols, not unwrappedSymbols. } if (symbol.Kind == SymbolKind.TypeParameter) { CrefSyntax crefSyntax = GetRootCrefSyntax(memberSyntax); diagnostics.Add(ErrorCode.WRN_BadXMLRefTypeVar, crefSyntax.Location, crefSyntax.ToString()); } else if (secondBest.IsFromCompilation == best.IsFromCompilation) { CrefSyntax crefSyntax = GetRootCrefSyntax(memberSyntax); int otherIndex = symbolIndex == 0 ? 1 : 0; diagnostics.Add(ErrorCode.WRN_AmbiguousXMLReference, crefSyntax.Location, crefSyntax.ToString(), symbol, symbols[otherIndex]); ambiguityWinner = ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, symbol); return symbols.SelectAsArray(sym => ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, sym)); } } else if (symbol.Kind == SymbolKind.TypeParameter) { CrefSyntax crefSyntax = GetRootCrefSyntax(memberSyntax); diagnostics.Add(ErrorCode.WRN_BadXMLRefTypeVar, crefSyntax.Location, crefSyntax.ToString()); } ambiguityWinner = null; return ImmutableArray.Create<Symbol>(ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, symbol)); } /// <summary> /// Replace any named type in the symbol list with its instance constructors. /// Construct all candidates with the implicitly-declared CrefTypeParameterSymbols. /// </summary> private void GetCrefOverloadResolutionCandidates(ImmutableArray<Symbol> symbols, int arity, TypeArgumentListSyntax? typeArgumentListSyntax, ArrayBuilder<Symbol> candidates) { foreach (Symbol candidate in symbols) { Symbol constructedCandidate = ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, candidate); NamedTypeSymbol? constructedCandidateType = constructedCandidate as NamedTypeSymbol; if ((object?)constructedCandidateType == null) { // Construct before overload resolution so the signatures will match. candidates.Add(constructedCandidate); } else { candidates.AddRange(constructedCandidateType.InstanceConstructors); } } } /// <summary> /// Given a list of method and/or property candidates, choose the first one (if any) with a signature /// that matches the parameter list in the cref. Return null if there isn't one. /// </summary> /// <remarks> /// Produces a diagnostic for ambiguous matches, but not for unresolved members - WRN_BadXMLRef is /// handled in BindMemberCref. /// </remarks> private static ImmutableArray<Symbol> PerformCrefOverloadResolution(ArrayBuilder<Symbol> candidates, ImmutableArray<ParameterSymbol> parameterSymbols, int arity, MemberCrefSyntax memberSyntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { ArrayBuilder<Symbol>? viable = null; foreach (Symbol candidate in candidates) { // BREAK: In dev11, any candidate with the type "dynamic" anywhere in its parameter list would be skipped // (see XmlDocCommentBinder::bindXmlReference). Apparently, this was because "the params that the xml doc // comments produce never will." This does not appear to have made sense in dev11 (skipping dropping the // candidate doesn't cause anything to blow up and may cause resolution to start succeeding) and it almost // certainly does not in roslyn (the signature comparer ignores the object-dynamic distinction anyway). Symbol signatureMember; switch (candidate.Kind) { case SymbolKind.Method: { MethodSymbol candidateMethod = (MethodSymbol)candidate; MethodKind candidateMethodKind = candidateMethod.MethodKind; bool candidateMethodIsVararg = candidateMethod.IsVararg; // If the arity from the cref is zero, then we accept methods of any arity. int signatureMemberArity = candidateMethodKind == MethodKind.Constructor ? 0 : (arity == 0 ? candidateMethod.Arity : arity); // CONSIDER: we might want to reuse this method symbol (as long as the MethodKind and Vararg-ness match). signatureMember = new SignatureOnlyMethodSymbol( methodKind: candidateMethodKind, typeParameters: IndexedTypeParameterSymbol.TakeSymbols(signatureMemberArity), parameters: parameterSymbols, // This specific comparer only looks for varargs. callingConvention: candidateMethodIsVararg ? Microsoft.Cci.CallingConvention.ExtraArguments : Microsoft.Cci.CallingConvention.HasThis, // These are ignored by this specific MemberSignatureComparer. containingType: null, name: null, refKind: RefKind.None, isInitOnly: false, isStatic: false, returnType: default, refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); break; } case SymbolKind.Property: { // CONSIDER: we might want to reuse this property symbol. signatureMember = new SignatureOnlyPropertySymbol( parameters: parameterSymbols, // These are ignored by this specific MemberSignatureComparer. containingType: null, name: null, refKind: RefKind.None, type: default, refCustomModifiers: ImmutableArray<CustomModifier>.Empty, isStatic: false, explicitInterfaceImplementations: ImmutableArray<PropertySymbol>.Empty); break; } case SymbolKind.NamedType: // Because we replaced them with constructors when we built the candidate list. throw ExceptionUtilities.UnexpectedValue(candidate.Kind); default: continue; } if (MemberSignatureComparer.CrefComparer.Equals(signatureMember, candidate)) { Debug.Assert(candidate.GetMemberArity() != 0 || candidate.Name == WellKnownMemberNames.InstanceConstructorName || arity == 0, "Can only have a 0-arity, non-constructor candidate if the desired arity is 0."); if (viable == null) { viable = ArrayBuilder<Symbol>.GetInstance(); viable.Add(candidate); } else { bool oldArityIsZero = viable[0].GetMemberArity() == 0; bool newArityIsZero = candidate.GetMemberArity() == 0; // If the cref specified arity 0 and the current candidate has arity 0 but the previous // match did not, then the current candidate is the unambiguous winner (unless there's // another match with arity 0 in a subsequent iteration). if (!oldArityIsZero || newArityIsZero) { if (!oldArityIsZero && newArityIsZero) { viable.Clear(); } viable.Add(candidate); } } } } if (viable == null) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } if (viable.Count > 1) { ambiguityWinner = viable[0]; CrefSyntax crefSyntax = GetRootCrefSyntax(memberSyntax); diagnostics.Add(ErrorCode.WRN_AmbiguousXMLReference, crefSyntax.Location, crefSyntax.ToString(), ambiguityWinner, viable[1]); } else { ambiguityWinner = null; } return viable.ToImmutableAndFree(); } /// <summary> /// If the member is generic, construct it with the CrefTypeParameterSymbols that should be in scope. /// </summary> private Symbol ConstructWithCrefTypeParameters(int arity, TypeArgumentListSyntax? typeArgumentListSyntax, Symbol symbol) { if (arity > 0) { Debug.Assert(typeArgumentListSyntax is object); SeparatedSyntaxList<TypeSyntax> typeArgumentSyntaxes = typeArgumentListSyntax.Arguments; var typeArgumentsWithAnnotations = ArrayBuilder<TypeWithAnnotations>.GetInstance(arity); var unusedDiagnostics = #if DEBUG new BindingDiagnosticBag(DiagnosticBag.GetInstance()); Debug.Assert(unusedDiagnostics.DiagnosticBag is object); #else BindingDiagnosticBag.Discarded; #endif for (int i = 0; i < arity; i++) { TypeSyntax typeArgumentSyntax = typeArgumentSyntaxes[i]; var typeArgument = BindType(typeArgumentSyntax, unusedDiagnostics); typeArgumentsWithAnnotations.Add(typeArgument); // Should be in a WithCrefTypeParametersBinder. Debug.Assert(typeArgumentSyntax.ContainsDiagnostics || !typeArgumentSyntax.SyntaxTree.ReportDocumentationCommentDiagnostics() || (!unusedDiagnostics.HasAnyErrors() && typeArgument.Type is CrefTypeParameterSymbol)); #if DEBUG unusedDiagnostics.DiagnosticBag.Clear(); #endif } #if DEBUG unusedDiagnostics.DiagnosticBag.Free(); #endif if (symbol.Kind == SymbolKind.Method) { symbol = ((MethodSymbol)symbol).Construct(typeArgumentsWithAnnotations.ToImmutableAndFree()); } else { Debug.Assert(symbol is NamedTypeSymbol); symbol = ((NamedTypeSymbol)symbol).Construct(typeArgumentsWithAnnotations.ToImmutableAndFree()); } } return symbol; } private ImmutableArray<ParameterSymbol> BindCrefParameters(BaseCrefParameterListSyntax parameterListSyntax, BindingDiagnosticBag diagnostics) { ArrayBuilder<ParameterSymbol> parameterBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(parameterListSyntax.Parameters.Count); foreach (CrefParameterSyntax parameter in parameterListSyntax.Parameters) { RefKind refKind = parameter.RefKindKeyword.Kind().GetRefKind(); Debug.Assert(parameterListSyntax.Parent is object); TypeSymbol type = BindCrefParameterOrReturnType(parameter.Type, (MemberCrefSyntax)parameterListSyntax.Parent, diagnostics); parameterBuilder.Add(new SignatureOnlyParameterSymbol(TypeWithAnnotations.Create(type), ImmutableArray<CustomModifier>.Empty, isParams: false, refKind: refKind)); } return parameterBuilder.ToImmutableAndFree(); } /// <remarks> /// Keep in sync with CSharpSemanticModel.GetSpeculativelyBoundExpressionWithoutNullability. /// </remarks> private TypeSymbol BindCrefParameterOrReturnType(TypeSyntax typeSyntax, MemberCrefSyntax memberCrefSyntax, BindingDiagnosticBag diagnostics) { // After much deliberation, we eventually decided to suppress lookup of inherited members within // crefs, in order to match dev11's behavior (Changeset #829014). Unfortunately, it turns out // that dev11 does not suppress these members when performing lookup within parameter and return // types, within crefs (DevDiv #586815, #598371). Debug.Assert(InCrefButNotParameterOrReturnType); Binder parameterOrReturnTypeBinder = this.WithAdditionalFlags(BinderFlags.CrefParameterOrReturnType); // It would be nice to pull this binder out of the factory so we wouldn't have to worry about them getting out // of sync, but this code is also used for included crefs, which don't have BinderFactories. // As a compromise, we'll assert that the binding locations match in scenarios where we can go through the factory. Debug.Assert(!this.Compilation.ContainsSyntaxTree(typeSyntax.SyntaxTree) || this.Compilation.GetBinderFactory(typeSyntax.SyntaxTree).GetBinder(typeSyntax).Flags == (parameterOrReturnTypeBinder.Flags & ~BinderFlags.SemanticModel)); var localDiagnostics = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), // Examined, but not reported. diagnostics.DependenciesBag); Debug.Assert(localDiagnostics.DiagnosticBag is object); TypeSymbol type = parameterOrReturnTypeBinder.BindType(typeSyntax, localDiagnostics).Type; if (localDiagnostics.HasAnyErrors()) { if (HasNonObsoleteError(localDiagnostics.DiagnosticBag)) { Debug.Assert(typeSyntax.Parent is object); ErrorCode code = typeSyntax.Parent.Kind() == SyntaxKind.ConversionOperatorMemberCref ? ErrorCode.WRN_BadXMLRefReturnType : ErrorCode.WRN_BadXMLRefParamType; CrefSyntax crefSyntax = GetRootCrefSyntax(memberCrefSyntax); diagnostics.Add(code, typeSyntax.Location, typeSyntax.ToString(), crefSyntax.ToString()); } } else { Debug.Assert(type.TypeKind != TypeKind.Error || typeSyntax.ContainsDiagnostics || !typeSyntax.SyntaxTree.ReportDocumentationCommentDiagnostics(), "Why wasn't there a diagnostic?"); } localDiagnostics.DiagnosticBag.Free(); return type; } private static bool HasNonObsoleteError(DiagnosticBag unusedDiagnostics) { foreach (Diagnostic diag in unusedDiagnostics.AsEnumerable()) { // CONSIDER: If this check is too slow, we could add a helper to DiagnosticBag // that checks for unrealized diagnostics without expanding them. switch ((ErrorCode)diag.Code) { case ErrorCode.ERR_DeprecatedSymbolStr: case ErrorCode.ERR_DeprecatedCollectionInitAddStr: break; default: if (diag.Severity == DiagnosticSeverity.Error) { return true; } break; } } return false; } private static CrefSyntax GetRootCrefSyntax(MemberCrefSyntax syntax) { SyntaxNode? parentSyntax = syntax.Parent; // Could be null when speculating. return parentSyntax == null || parentSyntax.IsKind(SyntaxKind.XmlCrefAttribute) ? syntax : (CrefSyntax)parentSyntax; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { internal ImmutableArray<Symbol> BindCref(CrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { ImmutableArray<Symbol> symbols = BindCrefInternal(syntax, out ambiguityWinner, diagnostics); Debug.Assert(!symbols.IsDefault, "Prefer empty to null."); Debug.Assert((symbols.Length > 1) == ((object?)ambiguityWinner != null), "ambiguityWinner should be set iff more than one symbol is returned."); return symbols; } private ImmutableArray<Symbol> BindCrefInternal(CrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { switch (syntax.Kind()) { case SyntaxKind.TypeCref: return BindTypeCref((TypeCrefSyntax)syntax, out ambiguityWinner, diagnostics); case SyntaxKind.QualifiedCref: return BindQualifiedCref((QualifiedCrefSyntax)syntax, out ambiguityWinner, diagnostics); case SyntaxKind.NameMemberCref: case SyntaxKind.IndexerMemberCref: case SyntaxKind.OperatorMemberCref: case SyntaxKind.ConversionOperatorMemberCref: return BindMemberCref((MemberCrefSyntax)syntax, containerOpt: null, ambiguityWinner: out ambiguityWinner, diagnostics: diagnostics); default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } private ImmutableArray<Symbol> BindTypeCref(TypeCrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { NamespaceOrTypeSymbol result = BindNamespaceOrTypeSymbolInCref(syntax.Type); // NOTE: we don't have to worry about the case where a non-error type is constructed // with erroneous type arguments, because only MemberCrefs have type arguments - // all other crefs only have type parameters. if (result.Kind == SymbolKind.ErrorType) { var noTrivia = syntax.WithLeadingTrivia(null).WithTrailingTrivia(null); diagnostics.Add(ErrorCode.WRN_BadXMLRef, syntax.Location, noTrivia.ToFullString()); } // We'll never have more than one type, but it is conceivable that result could // be an ExtendedErrorTypeSymbol with multiple candidates. ambiguityWinner = null; return ImmutableArray.Create<Symbol>(result); } private ImmutableArray<Symbol> BindQualifiedCref(QualifiedCrefSyntax syntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { // NOTE: we won't check whether container is an error type - we'll just let BindMemberCref fail // and report a blanket diagnostic. NamespaceOrTypeSymbol container = BindNamespaceOrTypeSymbolInCref(syntax.Container); return BindMemberCref(syntax.Member, container, out ambiguityWinner, diagnostics); } /// <summary> /// We can't use BindNamespaceOrTypeSymbol, since it doesn't return inaccessible symbols (directly). /// </summary> /// <remarks> /// Guaranteed not to return null. /// /// CONSIDER: As in dev11, we don't handle ambiguity at this level. Hypothetically, /// we could just pick one, though an "ideal" solution would probably involve a search /// down all ambiguous branches. /// </remarks> private NamespaceOrTypeSymbol BindNamespaceOrTypeSymbolInCref(TypeSyntax syntax) { Debug.Assert(Flags.Includes(BinderFlags.Cref)); // BREAK: Dev11 used to do a second lookup, ignoring accessibility, if the first lookup failed. // VS BUG#3321137: we need to try to find accessible members first // especially for compiler generated events (the backing field is private // but has the same name as the public event, and there is no easy way to // set the isEvent field on imported MEMBVARSYMs) // Diagnostics that don't prevent us from getting a symbol don't matter - the caller will report // an umbrella diagnostic if the result is an error type. NamespaceOrTypeSymbol namespaceOrTypeSymbol = BindNamespaceOrTypeSymbol(syntax, BindingDiagnosticBag.Discarded).NamespaceOrTypeSymbol; Debug.Assert((object)namespaceOrTypeSymbol != null); return namespaceOrTypeSymbol; } private ImmutableArray<Symbol> BindMemberCref(MemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { if ((object?)containerOpt != null && containerOpt.Kind == SymbolKind.TypeParameter) { // As in normal lookup (see CreateErrorIfLookupOnTypeParameter), you can't dot into a type parameter // (though you can dot into an expression of type parameter type). CrefSyntax crefSyntax = GetRootCrefSyntax(syntax); var noTrivia = syntax.WithLeadingTrivia(null).WithTrailingTrivia(null); diagnostics.Add(ErrorCode.WRN_BadXMLRef, crefSyntax.Location, noTrivia.ToFullString()); ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } ImmutableArray<Symbol> result; switch (syntax.Kind()) { case SyntaxKind.NameMemberCref: result = BindNameMemberCref((NameMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics); break; case SyntaxKind.IndexerMemberCref: result = BindIndexerMemberCref((IndexerMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics); break; case SyntaxKind.OperatorMemberCref: result = BindOperatorMemberCref((OperatorMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics); break; case SyntaxKind.ConversionOperatorMemberCref: result = BindConversionOperatorMemberCref((ConversionOperatorMemberCrefSyntax)syntax, containerOpt, out ambiguityWinner, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } if (!result.Any()) { CrefSyntax crefSyntax = GetRootCrefSyntax(syntax); var noTrivia = syntax.WithLeadingTrivia(null).WithTrailingTrivia(null); diagnostics.Add(ErrorCode.WRN_BadXMLRef, crefSyntax.Location, noTrivia.ToFullString()); } return result; } private ImmutableArray<Symbol> BindNameMemberCref(NameMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { SimpleNameSyntax? nameSyntax = syntax.Name as SimpleNameSyntax; int arity; string memberName; if (nameSyntax != null) { arity = nameSyntax.Arity; memberName = nameSyntax.Identifier.ValueText; } else { // If the name isn't a SimpleNameSyntax, then we must have a type name followed by a parameter list. // Thus, we're looking for a constructor. Debug.Assert((object?)containerOpt == null); // Could be an error type, but we'll just lookup fail below. containerOpt = BindNamespaceOrTypeSymbolInCref(syntax.Name); arity = 0; memberName = WellKnownMemberNames.InstanceConstructorName; } if (string.IsNullOrEmpty(memberName)) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } ImmutableArray<Symbol> sortedSymbols = ComputeSortedCrefMembers(syntax, containerOpt, memberName, arity, syntax.Parameters != null, diagnostics); if (sortedSymbols.IsEmpty) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } return ProcessCrefMemberLookupResults( sortedSymbols, arity, syntax, typeArgumentListSyntax: arity == 0 ? null : ((GenericNameSyntax)nameSyntax!).TypeArgumentList, parameterListSyntax: syntax.Parameters, ambiguityWinner: out ambiguityWinner, diagnostics: diagnostics); } private ImmutableArray<Symbol> BindIndexerMemberCref(IndexerMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { const int arity = 0; ImmutableArray<Symbol> sortedSymbols = ComputeSortedCrefMembers(syntax, containerOpt, WellKnownMemberNames.Indexer, arity, syntax.Parameters != null, diagnostics); if (sortedSymbols.IsEmpty) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } // Since only indexers are named WellKnownMemberNames.Indexer. Debug.Assert(sortedSymbols.All(SymbolExtensions.IsIndexer)); // NOTE: guaranteed to be a property, because only indexers are considered. return ProcessCrefMemberLookupResults( sortedSymbols, arity, syntax, typeArgumentListSyntax: null, parameterListSyntax: syntax.Parameters, ambiguityWinner: out ambiguityWinner, diagnostics: diagnostics); } // NOTE: not guaranteed to be a method (e.g. class op_Addition) // NOTE: constructor fallback logic applies private ImmutableArray<Symbol> BindOperatorMemberCref(OperatorMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { const int arity = 0; CrefParameterListSyntax? parameterListSyntax = syntax.Parameters; // NOTE: Prefer binary to unary, unless there is exactly one parameter. // CONSIDER: we're following dev11 by never using a binary operator name if there's // exactly one parameter, but doing so would allow us to match single-parameter constructors. SyntaxKind operatorTokenKind = syntax.OperatorToken.Kind(); string? memberName = parameterListSyntax != null && parameterListSyntax.Parameters.Count == 1 ? null : OperatorFacts.BinaryOperatorNameFromSyntaxKindIfAny(operatorTokenKind); memberName = memberName ?? OperatorFacts.UnaryOperatorNameFromSyntaxKindIfAny(operatorTokenKind); if (memberName == null) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } ImmutableArray<Symbol> sortedSymbols = ComputeSortedCrefMembers(syntax, containerOpt, memberName, arity, syntax.Parameters != null, diagnostics); if (sortedSymbols.IsEmpty) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } return ProcessCrefMemberLookupResults( sortedSymbols, arity, syntax, typeArgumentListSyntax: null, parameterListSyntax: parameterListSyntax, ambiguityWinner: out ambiguityWinner, diagnostics: diagnostics); } // NOTE: not guaranteed to be a method (e.g. class op_Implicit) private ImmutableArray<Symbol> BindConversionOperatorMemberCref(ConversionOperatorMemberCrefSyntax syntax, NamespaceOrTypeSymbol? containerOpt, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { const int arity = 0; string memberName = syntax.ImplicitOrExplicitKeyword.Kind() == SyntaxKind.ImplicitKeyword ? WellKnownMemberNames.ImplicitConversionName : WellKnownMemberNames.ExplicitConversionName; ImmutableArray<Symbol> sortedSymbols = ComputeSortedCrefMembers(syntax, containerOpt, memberName, arity, syntax.Parameters != null, diagnostics); if (sortedSymbols.IsEmpty) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } TypeSymbol returnType = BindCrefParameterOrReturnType(syntax.Type, syntax, diagnostics); // Filter out methods with the wrong return type, since overload resolution won't catch these. sortedSymbols = sortedSymbols.WhereAsArray((symbol, returnType) => symbol.Kind != SymbolKind.Method || TypeSymbol.Equals(((MethodSymbol)symbol).ReturnType, returnType, TypeCompareKind.ConsiderEverything2), returnType); if (!sortedSymbols.Any()) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } return ProcessCrefMemberLookupResults( sortedSymbols, arity, syntax, typeArgumentListSyntax: null, parameterListSyntax: syntax.Parameters, ambiguityWinner: out ambiguityWinner, diagnostics: diagnostics); } /// <summary> /// Perform lookup (optionally, in a specified container). If nothing is found and the member name matches the containing type /// name, then use the instance constructors of the type instead. The resulting symbols are sorted since tie-breaking is based /// on order and we want cref binding to be repeatable. /// </summary> /// <remarks> /// Never returns null. /// </remarks> private ImmutableArray<Symbol> ComputeSortedCrefMembers(CSharpSyntaxNode syntax, NamespaceOrTypeSymbol? containerOpt, string memberName, int arity, bool hasParameterList, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var result = ComputeSortedCrefMembers(containerOpt, memberName, arity, hasParameterList, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return result; } private ImmutableArray<Symbol> ComputeSortedCrefMembers(NamespaceOrTypeSymbol? containerOpt, string memberName, int arity, bool hasParameterList, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Since we may find symbols without going through the lookup API, // expose the symbols via an ArrayBuilder. ArrayBuilder<Symbol> builder; { LookupResult result = LookupResult.GetInstance(); this.LookupSymbolsOrMembersInternal( result, containerOpt, name: memberName, arity: arity, basesBeingResolved: null, options: LookupOptions.AllMethodsOnArityZero, diagnose: false, useSiteInfo: ref useSiteInfo); // CONSIDER: Dev11 also checks for a constructor in the event of an ambiguous result. if (result.IsMultiViable) { // Dev11 doesn't consider members from System.Object when the container is an interface. // Lookup should already have dropped such members. builder = ArrayBuilder<Symbol>.GetInstance(); builder.AddRange(result.Symbols); result.Free(); } else { result.Free(); // Won't be using this. // Dev11 has a complicated two-stage process for determining when a cref is really referring to a constructor. // Under two sets of conditions, XmlDocCommentBinder::bindXMLReferenceName will decide that a name refers // to a constructor and under one set of conditions, the calling method, XmlDocCommentBinder::bindXMLReference, // will roll back that decision and return null. // In XmlDocCommentBinder::bindXMLReferenceName: // 1) If an unqualified, non-generic name didn't bind to anything and the name matches the name of the type // to which the doc comment is applied, then bind to a constructor. // 2) If a qualified, non-generic name didn't bind to anything and the LHS of the qualified name is a type // with the same name, then bind to a constructor. // Quoted from XmlDocCommentBinder::bindXMLReference: // Filtering out the case where specifying the name of a generic type without specifying // any arity returns a constructor. This case shouldn't return anything. Note that // returning the constructors was a fix for the wonky constructor behavior, but in order // to not introduce a regression and breaking change we return NULL in this case. // e.g. // // /// <see cref="Goo"/> // class Goo<T> { } // // This cref used not to bind to anything, because before it was looking for a type and // since there was no arity, it didn't find Goo<T>. Now however, it finds Goo<T>.ctor, // which is arguably correct, but would be a breaking change (albeit with minimal impact) // so we catch this case and chuck out the symbol found. // In Roslyn, we're doing everything in one pass, rather than guessing and rolling back. // As in the native compiler, we treat this as a fallback case - something that actually has the // specified name is preferred. NamedTypeSymbol? constructorType = null; if (arity == 0) // Member arity { NamedTypeSymbol? containerType = containerOpt as NamedTypeSymbol; if ((object?)containerType != null) { // Case 1: If the name is qualified by a type with the same name, then we want a // constructor (unless the type is generic, the cref is on/in the type (but not // on/in a nested type), and there were no parens after the member name). if (containerType.Name == memberName && (hasParameterList || containerType.Arity == 0 || !TypeSymbol.Equals(this.ContainingType, containerType.OriginalDefinition, TypeCompareKind.ConsiderEverything2))) { constructorType = containerType; } } else if ((object?)containerOpt == null && hasParameterList) { // Case 2: If the name is not qualified by anything, but we're in the scope // of a type with the same name (regardless of arity), then we want a constructor, // as long as there were parens after the member name. NamedTypeSymbol? binderContainingType = this.ContainingType; if ((object?)binderContainingType != null && memberName == binderContainingType.Name) { constructorType = binderContainingType; } } } if ((object?)constructorType != null) { ImmutableArray<MethodSymbol> instanceConstructors = constructorType.InstanceConstructors; int numInstanceConstructors = instanceConstructors.Length; if (numInstanceConstructors == 0) { return ImmutableArray<Symbol>.Empty; } builder = ArrayBuilder<Symbol>.GetInstance(numInstanceConstructors); builder.AddRange(instanceConstructors); } else { return ImmutableArray<Symbol>.Empty; } } } Debug.Assert(builder != null); // Since we resolve ambiguities by just picking the first symbol we encounter, // the order of the symbols matters for repeatability. if (builder.Count > 1) { builder.Sort(ConsistentSymbolOrder.Instance); } return builder.ToImmutableAndFree(); } /// <summary> /// Given a list of viable lookup results (based on the name, arity, and containing symbol), /// attempt to select one. /// </summary> private ImmutableArray<Symbol> ProcessCrefMemberLookupResults( ImmutableArray<Symbol> symbols, int arity, MemberCrefSyntax memberSyntax, TypeArgumentListSyntax? typeArgumentListSyntax, BaseCrefParameterListSyntax? parameterListSyntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { Debug.Assert(!symbols.IsEmpty); if (parameterListSyntax == null) { return ProcessParameterlessCrefMemberLookupResults(symbols, arity, memberSyntax, typeArgumentListSyntax, out ambiguityWinner, diagnostics); } ArrayBuilder<Symbol> candidates = ArrayBuilder<Symbol>.GetInstance(); GetCrefOverloadResolutionCandidates(symbols, arity, typeArgumentListSyntax, candidates); ImmutableArray<ParameterSymbol> parameterSymbols = BindCrefParameters(parameterListSyntax, diagnostics); ImmutableArray<Symbol> results = PerformCrefOverloadResolution(candidates, parameterSymbols, arity, memberSyntax, out ambiguityWinner, diagnostics); candidates.Free(); // NOTE: This diagnostic is just a hint that might help fix a broken cref, so don't do // any work unless there are no viable candidates. if (results.Length == 0) { for (int i = 0; i < parameterSymbols.Length; i++) { if (ContainsNestedTypeOfUnconstructedGenericType(parameterSymbols[i].Type)) { // This warning is new in Roslyn, because our better-defined semantics for // cref lookup disallow some things that were possible in dev12. // // Consider the following code: // // public class C<T> // { // public class Inner { } // // public void M(Inner i) { } // // /// <see cref="M"/> // /// <see cref="C{T}.M"/> // /// <see cref="C{Q}.M"/> // /// <see cref="C{Q}.M(C{Q}.Inner)"/> // /// <see cref="C{Q}.M(Inner)"/> // WRN_UnqualifiedNestedTypeInCref // public void N() { } // } // // Dev12 binds all of the crefs as "M:C`1.M(C{`0}.Inner)". // Roslyn accepts all but the last. The issue is that the context for performing // the lookup is not C<Q>, but C<T>. Consequently, Inner binds to C<T>.Inner and // then overload resolution fails because C<T>.Inner does not match C<Q>.Inner, // the parameter type of C<Q>.M. Since we could not agree that the old behavior // was desirable (other than for backwards compatibility) and since mimicking it // would have been expensive, we settled on introducing a new warning that at // least hints to the user how then can work around the issue (i.e. by qualifying // Inner as C{Q}.Inner). Additional details are available in DevDiv #743425. // // CONSIDER: We could actually put the qualified form in the warning message, // but that would probably just make it more frustrating (i.e. if the compiler // knows exactly what I mean, why do I have to type it). // // NOTE: This is not a great location (whole parameter instead of problematic type), // but it's better than nothing. diagnostics.Add(ErrorCode.WRN_UnqualifiedNestedTypeInCref, parameterListSyntax.Parameters[i].Location); break; } } } return results; } private static bool ContainsNestedTypeOfUnconstructedGenericType(TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Array: return ContainsNestedTypeOfUnconstructedGenericType(((ArrayTypeSymbol)type).ElementType); case TypeKind.Pointer: return ContainsNestedTypeOfUnconstructedGenericType(((PointerTypeSymbol)type).PointedAtType); case TypeKind.FunctionPointer: MethodSymbol signature = ((FunctionPointerTypeSymbol)type).Signature; if (ContainsNestedTypeOfUnconstructedGenericType(signature.ReturnType)) { return true; } foreach (var param in signature.Parameters) { if (ContainsNestedTypeOfUnconstructedGenericType(param.Type)) { return true; } } return false; case TypeKind.Delegate: case TypeKind.Class: case TypeKind.Interface: case TypeKind.Struct: case TypeKind.Enum: case TypeKind.Error: NamedTypeSymbol namedType = (NamedTypeSymbol)type; if (IsNestedTypeOfUnconstructedGenericType(namedType)) { return true; } foreach (TypeWithAnnotations typeArgument in namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { if (ContainsNestedTypeOfUnconstructedGenericType(typeArgument.Type)) { return true; } } return false; case TypeKind.Dynamic: case TypeKind.TypeParameter: return false; default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private static bool IsNestedTypeOfUnconstructedGenericType(NamedTypeSymbol type) { NamedTypeSymbol containing = type.ContainingType; while ((object)containing != null) { if (containing.Arity > 0 && containing.IsDefinition) { return true; } containing = containing.ContainingType; } return false; } /// <summary> /// At this point, we have a list of viable symbols and no parameter list with which to perform /// overload resolution. We'll just return the first symbol, giving a diagnostic if there are /// others. /// Caveat: If there are multiple candidates and only one is from source, then the source symbol /// wins and no diagnostic is reported. /// </summary> private ImmutableArray<Symbol> ProcessParameterlessCrefMemberLookupResults( ImmutableArray<Symbol> symbols, int arity, MemberCrefSyntax memberSyntax, TypeArgumentListSyntax? typeArgumentListSyntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { // If the syntax indicates arity zero, then we match methods of any arity. // However, if there are both generic and non-generic methods, then the // generic methods should be ignored. if (symbols.Length > 1 && arity == 0) { bool hasNonGenericMethod = false; bool hasGenericMethod = false; foreach (Symbol s in symbols) { if (s.Kind != SymbolKind.Method) { continue; } if (((MethodSymbol)s).Arity == 0) { hasNonGenericMethod = true; } else { hasGenericMethod = true; } if (hasGenericMethod && hasNonGenericMethod) { break; //Nothing else to be learned. } } if (hasNonGenericMethod && hasGenericMethod) { symbols = symbols.WhereAsArray(s => s.Kind != SymbolKind.Method || ((MethodSymbol)s).Arity == 0); } } Debug.Assert(!symbols.IsEmpty); Symbol symbol = symbols[0]; // If there's ambiguity, prefer source symbols. // Logic is similar to ResultSymbol, but separate because the error handling is totally different. if (symbols.Length > 1) { // Size is known, but IndexOfSymbolFromCurrentCompilation expects a builder. ArrayBuilder<Symbol> unwrappedSymbols = ArrayBuilder<Symbol>.GetInstance(symbols.Length); foreach (Symbol wrapped in symbols) { unwrappedSymbols.Add(UnwrapAliasNoDiagnostics(wrapped)); } BestSymbolInfo secondBest; BestSymbolInfo best = GetBestSymbolInfo(unwrappedSymbols, out secondBest); Debug.Assert(!best.IsNone); Debug.Assert(!secondBest.IsNone); unwrappedSymbols.Free(); int symbolIndex = 0; if (best.IsFromCompilation) { symbolIndex = best.Index; symbol = symbols[symbolIndex]; // NOTE: symbols, not unwrappedSymbols. } if (symbol.Kind == SymbolKind.TypeParameter) { CrefSyntax crefSyntax = GetRootCrefSyntax(memberSyntax); diagnostics.Add(ErrorCode.WRN_BadXMLRefTypeVar, crefSyntax.Location, crefSyntax.ToString()); } else if (secondBest.IsFromCompilation == best.IsFromCompilation) { CrefSyntax crefSyntax = GetRootCrefSyntax(memberSyntax); int otherIndex = symbolIndex == 0 ? 1 : 0; diagnostics.Add(ErrorCode.WRN_AmbiguousXMLReference, crefSyntax.Location, crefSyntax.ToString(), symbol, symbols[otherIndex]); ambiguityWinner = ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, symbol); return symbols.SelectAsArray(sym => ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, sym)); } } else if (symbol.Kind == SymbolKind.TypeParameter) { CrefSyntax crefSyntax = GetRootCrefSyntax(memberSyntax); diagnostics.Add(ErrorCode.WRN_BadXMLRefTypeVar, crefSyntax.Location, crefSyntax.ToString()); } ambiguityWinner = null; return ImmutableArray.Create<Symbol>(ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, symbol)); } /// <summary> /// Replace any named type in the symbol list with its instance constructors. /// Construct all candidates with the implicitly-declared CrefTypeParameterSymbols. /// </summary> private void GetCrefOverloadResolutionCandidates(ImmutableArray<Symbol> symbols, int arity, TypeArgumentListSyntax? typeArgumentListSyntax, ArrayBuilder<Symbol> candidates) { foreach (Symbol candidate in symbols) { Symbol constructedCandidate = ConstructWithCrefTypeParameters(arity, typeArgumentListSyntax, candidate); NamedTypeSymbol? constructedCandidateType = constructedCandidate as NamedTypeSymbol; if ((object?)constructedCandidateType == null) { // Construct before overload resolution so the signatures will match. candidates.Add(constructedCandidate); } else { candidates.AddRange(constructedCandidateType.InstanceConstructors); } } } /// <summary> /// Given a list of method and/or property candidates, choose the first one (if any) with a signature /// that matches the parameter list in the cref. Return null if there isn't one. /// </summary> /// <remarks> /// Produces a diagnostic for ambiguous matches, but not for unresolved members - WRN_BadXMLRef is /// handled in BindMemberCref. /// </remarks> private static ImmutableArray<Symbol> PerformCrefOverloadResolution(ArrayBuilder<Symbol> candidates, ImmutableArray<ParameterSymbol> parameterSymbols, int arity, MemberCrefSyntax memberSyntax, out Symbol? ambiguityWinner, BindingDiagnosticBag diagnostics) { ArrayBuilder<Symbol>? viable = null; foreach (Symbol candidate in candidates) { // BREAK: In dev11, any candidate with the type "dynamic" anywhere in its parameter list would be skipped // (see XmlDocCommentBinder::bindXmlReference). Apparently, this was because "the params that the xml doc // comments produce never will." This does not appear to have made sense in dev11 (skipping dropping the // candidate doesn't cause anything to blow up and may cause resolution to start succeeding) and it almost // certainly does not in roslyn (the signature comparer ignores the object-dynamic distinction anyway). Symbol signatureMember; switch (candidate.Kind) { case SymbolKind.Method: { MethodSymbol candidateMethod = (MethodSymbol)candidate; MethodKind candidateMethodKind = candidateMethod.MethodKind; bool candidateMethodIsVararg = candidateMethod.IsVararg; // If the arity from the cref is zero, then we accept methods of any arity. int signatureMemberArity = candidateMethodKind == MethodKind.Constructor ? 0 : (arity == 0 ? candidateMethod.Arity : arity); // CONSIDER: we might want to reuse this method symbol (as long as the MethodKind and Vararg-ness match). signatureMember = new SignatureOnlyMethodSymbol( methodKind: candidateMethodKind, typeParameters: IndexedTypeParameterSymbol.TakeSymbols(signatureMemberArity), parameters: parameterSymbols, // This specific comparer only looks for varargs. callingConvention: candidateMethodIsVararg ? Microsoft.Cci.CallingConvention.ExtraArguments : Microsoft.Cci.CallingConvention.HasThis, // These are ignored by this specific MemberSignatureComparer. containingType: null, name: null, refKind: RefKind.None, isInitOnly: false, isStatic: false, returnType: default, refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); break; } case SymbolKind.Property: { // CONSIDER: we might want to reuse this property symbol. signatureMember = new SignatureOnlyPropertySymbol( parameters: parameterSymbols, // These are ignored by this specific MemberSignatureComparer. containingType: null, name: null, refKind: RefKind.None, type: default, refCustomModifiers: ImmutableArray<CustomModifier>.Empty, isStatic: false, explicitInterfaceImplementations: ImmutableArray<PropertySymbol>.Empty); break; } case SymbolKind.NamedType: // Because we replaced them with constructors when we built the candidate list. throw ExceptionUtilities.UnexpectedValue(candidate.Kind); default: continue; } if (MemberSignatureComparer.CrefComparer.Equals(signatureMember, candidate)) { Debug.Assert(candidate.GetMemberArity() != 0 || candidate.Name == WellKnownMemberNames.InstanceConstructorName || arity == 0, "Can only have a 0-arity, non-constructor candidate if the desired arity is 0."); if (viable == null) { viable = ArrayBuilder<Symbol>.GetInstance(); viable.Add(candidate); } else { bool oldArityIsZero = viable[0].GetMemberArity() == 0; bool newArityIsZero = candidate.GetMemberArity() == 0; // If the cref specified arity 0 and the current candidate has arity 0 but the previous // match did not, then the current candidate is the unambiguous winner (unless there's // another match with arity 0 in a subsequent iteration). if (!oldArityIsZero || newArityIsZero) { if (!oldArityIsZero && newArityIsZero) { viable.Clear(); } viable.Add(candidate); } } } } if (viable == null) { ambiguityWinner = null; return ImmutableArray<Symbol>.Empty; } if (viable.Count > 1) { ambiguityWinner = viable[0]; CrefSyntax crefSyntax = GetRootCrefSyntax(memberSyntax); diagnostics.Add(ErrorCode.WRN_AmbiguousXMLReference, crefSyntax.Location, crefSyntax.ToString(), ambiguityWinner, viable[1]); } else { ambiguityWinner = null; } return viable.ToImmutableAndFree(); } /// <summary> /// If the member is generic, construct it with the CrefTypeParameterSymbols that should be in scope. /// </summary> private Symbol ConstructWithCrefTypeParameters(int arity, TypeArgumentListSyntax? typeArgumentListSyntax, Symbol symbol) { if (arity > 0) { Debug.Assert(typeArgumentListSyntax is object); SeparatedSyntaxList<TypeSyntax> typeArgumentSyntaxes = typeArgumentListSyntax.Arguments; var typeArgumentsWithAnnotations = ArrayBuilder<TypeWithAnnotations>.GetInstance(arity); var unusedDiagnostics = #if DEBUG new BindingDiagnosticBag(DiagnosticBag.GetInstance()); Debug.Assert(unusedDiagnostics.DiagnosticBag is object); #else BindingDiagnosticBag.Discarded; #endif for (int i = 0; i < arity; i++) { TypeSyntax typeArgumentSyntax = typeArgumentSyntaxes[i]; var typeArgument = BindType(typeArgumentSyntax, unusedDiagnostics); typeArgumentsWithAnnotations.Add(typeArgument); // Should be in a WithCrefTypeParametersBinder. Debug.Assert(typeArgumentSyntax.ContainsDiagnostics || !typeArgumentSyntax.SyntaxTree.ReportDocumentationCommentDiagnostics() || (!unusedDiagnostics.HasAnyErrors() && typeArgument.Type is CrefTypeParameterSymbol)); #if DEBUG unusedDiagnostics.DiagnosticBag.Clear(); #endif } #if DEBUG unusedDiagnostics.DiagnosticBag.Free(); #endif if (symbol.Kind == SymbolKind.Method) { symbol = ((MethodSymbol)symbol).Construct(typeArgumentsWithAnnotations.ToImmutableAndFree()); } else { Debug.Assert(symbol is NamedTypeSymbol); symbol = ((NamedTypeSymbol)symbol).Construct(typeArgumentsWithAnnotations.ToImmutableAndFree()); } } return symbol; } private ImmutableArray<ParameterSymbol> BindCrefParameters(BaseCrefParameterListSyntax parameterListSyntax, BindingDiagnosticBag diagnostics) { ArrayBuilder<ParameterSymbol> parameterBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(parameterListSyntax.Parameters.Count); foreach (CrefParameterSyntax parameter in parameterListSyntax.Parameters) { RefKind refKind = parameter.RefKindKeyword.Kind().GetRefKind(); Debug.Assert(parameterListSyntax.Parent is object); TypeSymbol type = BindCrefParameterOrReturnType(parameter.Type, (MemberCrefSyntax)parameterListSyntax.Parent, diagnostics); parameterBuilder.Add(new SignatureOnlyParameterSymbol(TypeWithAnnotations.Create(type), ImmutableArray<CustomModifier>.Empty, isParams: false, refKind: refKind)); } return parameterBuilder.ToImmutableAndFree(); } /// <remarks> /// Keep in sync with CSharpSemanticModel.GetSpeculativelyBoundExpressionWithoutNullability. /// </remarks> private TypeSymbol BindCrefParameterOrReturnType(TypeSyntax typeSyntax, MemberCrefSyntax memberCrefSyntax, BindingDiagnosticBag diagnostics) { // After much deliberation, we eventually decided to suppress lookup of inherited members within // crefs, in order to match dev11's behavior (Changeset #829014). Unfortunately, it turns out // that dev11 does not suppress these members when performing lookup within parameter and return // types, within crefs (DevDiv #586815, #598371). Debug.Assert(InCrefButNotParameterOrReturnType); Binder parameterOrReturnTypeBinder = this.WithAdditionalFlags(BinderFlags.CrefParameterOrReturnType); // It would be nice to pull this binder out of the factory so we wouldn't have to worry about them getting out // of sync, but this code is also used for included crefs, which don't have BinderFactories. // As a compromise, we'll assert that the binding locations match in scenarios where we can go through the factory. Debug.Assert(!this.Compilation.ContainsSyntaxTree(typeSyntax.SyntaxTree) || this.Compilation.GetBinderFactory(typeSyntax.SyntaxTree).GetBinder(typeSyntax).Flags == (parameterOrReturnTypeBinder.Flags & ~BinderFlags.SemanticModel)); var localDiagnostics = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), // Examined, but not reported. diagnostics.DependenciesBag); Debug.Assert(localDiagnostics.DiagnosticBag is object); TypeSymbol type = parameterOrReturnTypeBinder.BindType(typeSyntax, localDiagnostics).Type; if (localDiagnostics.HasAnyErrors()) { if (HasNonObsoleteError(localDiagnostics.DiagnosticBag)) { Debug.Assert(typeSyntax.Parent is object); ErrorCode code = typeSyntax.Parent.Kind() == SyntaxKind.ConversionOperatorMemberCref ? ErrorCode.WRN_BadXMLRefReturnType : ErrorCode.WRN_BadXMLRefParamType; CrefSyntax crefSyntax = GetRootCrefSyntax(memberCrefSyntax); diagnostics.Add(code, typeSyntax.Location, typeSyntax.ToString(), crefSyntax.ToString()); } } else { Debug.Assert(type.TypeKind != TypeKind.Error || typeSyntax.ContainsDiagnostics || !typeSyntax.SyntaxTree.ReportDocumentationCommentDiagnostics(), "Why wasn't there a diagnostic?"); } localDiagnostics.DiagnosticBag.Free(); return type; } private static bool HasNonObsoleteError(DiagnosticBag unusedDiagnostics) { foreach (Diagnostic diag in unusedDiagnostics.AsEnumerable()) { // CONSIDER: If this check is too slow, we could add a helper to DiagnosticBag // that checks for unrealized diagnostics without expanding them. switch ((ErrorCode)diag.Code) { case ErrorCode.ERR_DeprecatedSymbolStr: case ErrorCode.ERR_DeprecatedCollectionInitAddStr: break; default: if (diag.Severity == DiagnosticSeverity.Error) { return true; } break; } } return false; } private static CrefSyntax GetRootCrefSyntax(MemberCrefSyntax syntax) { SyntaxNode? parentSyntax = syntax.Parent; // Could be null when speculating. return parentSyntax == null || parentSyntax.IsKind(SyntaxKind.XmlCrefAttribute) ? syntax : (CrefSyntax)parentSyntax; } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./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
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Scripting/CSharp/PublicAPI.Shipped.txt
Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter Microsoft.CodeAnalysis.CSharp.Scripting.ScriptOptionsExtensions override Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter.FormatException(System.Exception e) -> string override Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter.FormatObject(object obj, Microsoft.CodeAnalysis.Scripting.Hosting.PrintOptions options) -> string static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.Create(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, System.Type globalsType = null, Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader assemblyLoader = null) -> Microsoft.CodeAnalysis.Scripting.Script<object> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.Create(System.IO.Stream code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, System.Type globalsType = null, Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader assemblyLoader = null) -> Microsoft.CodeAnalysis.Scripting.Script<object> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.Create<T>(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, System.Type globalsType = null, Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader assemblyLoader = null) -> Microsoft.CodeAnalysis.Scripting.Script<T> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.Create<T>(System.IO.Stream code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, System.Type globalsType = null, Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader assemblyLoader = null) -> Microsoft.CodeAnalysis.Scripting.Script<T> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.EvaluateAsync(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, object globals = null, System.Type globalsType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<object> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.EvaluateAsync<T>(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, object globals = null, System.Type globalsType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<T> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.RunAsync(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, object globals = null, System.Type globalsType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Scripting.ScriptState<object>> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.RunAsync<T>(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, object globals = null, System.Type globalsType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Scripting.ScriptState<T>> static Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter.Instance.get -> Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter static Microsoft.CodeAnalysis.CSharp.Scripting.ScriptOptionsExtensions.WithLanguageVersion(this Microsoft.CodeAnalysis.Scripting.ScriptOptions options, Microsoft.CodeAnalysis.CSharp.LanguageVersion languageVersion) -> Microsoft.CodeAnalysis.Scripting.ScriptOptions
Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter Microsoft.CodeAnalysis.CSharp.Scripting.ScriptOptionsExtensions override Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter.FormatException(System.Exception e) -> string override Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter.FormatObject(object obj, Microsoft.CodeAnalysis.Scripting.Hosting.PrintOptions options) -> string static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.Create(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, System.Type globalsType = null, Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader assemblyLoader = null) -> Microsoft.CodeAnalysis.Scripting.Script<object> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.Create(System.IO.Stream code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, System.Type globalsType = null, Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader assemblyLoader = null) -> Microsoft.CodeAnalysis.Scripting.Script<object> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.Create<T>(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, System.Type globalsType = null, Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader assemblyLoader = null) -> Microsoft.CodeAnalysis.Scripting.Script<T> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.Create<T>(System.IO.Stream code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, System.Type globalsType = null, Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader assemblyLoader = null) -> Microsoft.CodeAnalysis.Scripting.Script<T> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.EvaluateAsync(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, object globals = null, System.Type globalsType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<object> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.EvaluateAsync<T>(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, object globals = null, System.Type globalsType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<T> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.RunAsync(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, object globals = null, System.Type globalsType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Scripting.ScriptState<object>> static Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.RunAsync<T>(string code, Microsoft.CodeAnalysis.Scripting.ScriptOptions options = null, object globals = null, System.Type globalsType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Scripting.ScriptState<T>> static Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter.Instance.get -> Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter static Microsoft.CodeAnalysis.CSharp.Scripting.ScriptOptionsExtensions.WithLanguageVersion(this Microsoft.CodeAnalysis.Scripting.ScriptOptions options, Microsoft.CodeAnalysis.CSharp.LanguageVersion languageVersion) -> Microsoft.CodeAnalysis.Scripting.ScriptOptions
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Workspaces/Core/Desktop/Workspace/Host/Mef/MefV1HostServices.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Collections.Immutable; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// A class that provides host services via classes instances exported via a MEF version 1 composition. /// </summary> public class MefV1HostServices : HostServices, IMefHostExportProvider { internal delegate MefV1HostServices CreationHook(IEnumerable<Assembly> assemblies); /// <summary> /// This delegate allows test code to override the behavior of <see cref="Create(IEnumerable{Assembly})"/>. /// </summary> /// <seealso cref="TestAccessor.HookServiceCreation"/> private static CreationHook s_CreationHook; // the export provider for the MEF composition private readonly ExportProvider _exportProvider; // accumulated cache for exports private ImmutableDictionary<ExportKey, IEnumerable> _exportsMap = ImmutableDictionary<ExportKey, IEnumerable>.Empty; private MefV1HostServices(ExportProvider exportProvider) { _exportProvider = exportProvider; } public static MefV1HostServices Create(ExportProvider exportProvider) { if (exportProvider == null) { throw new ArgumentNullException(nameof(exportProvider)); } return new MefV1HostServices(exportProvider); } public static MefV1HostServices Create(IEnumerable<Assembly> assemblies) { if (assemblies == null) { throw new ArgumentNullException(nameof(assemblies)); } if (s_CreationHook != null) { return s_CreationHook(assemblies); } var catalog = new AggregateCatalog(assemblies.Select(a => new AssemblyCatalog(a))); var container = new CompositionContainer(catalog, compositionOptions: CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe); return new MefV1HostServices(container); } /// <summary> /// Creates a new <see cref="HostWorkspaceServices"/> associated with the specified workspace. /// </summary> protected internal override HostWorkspaceServices CreateWorkspaceServices(Workspace workspace) { return new MefWorkspaceServices(this, workspace); } /// <summary> /// Gets all the MEF exports of the specified type with the specified metadata. /// </summary> public IEnumerable<Lazy<TExtension, TMetadata>> GetExports<TExtension, TMetadata>() { var key = new ExportKey(typeof(TExtension).AssemblyQualifiedName, typeof(TMetadata).AssemblyQualifiedName); if (!_exportsMap.TryGetValue(key, out var exports)) { exports = ImmutableInterlocked.GetOrAdd(ref _exportsMap, key, _ => { return _exportProvider.GetExports<TExtension, TMetadata>().ToImmutableArray(); }); } return (IEnumerable<Lazy<TExtension, TMetadata>>)exports; } /// <summary> /// Gets all the MEF exports of the specified type. /// </summary> public IEnumerable<Lazy<TExtension>> GetExports<TExtension>() { var key = new ExportKey(typeof(TExtension).AssemblyQualifiedName, ""); if (!_exportsMap.TryGetValue(key, out var exports)) { exports = ImmutableInterlocked.GetOrAdd(ref _exportsMap, key, _ => _exportProvider.GetExports<TExtension>().ToImmutableArray()); } return (IEnumerable<Lazy<TExtension>>)exports; } internal TestAccessor GetTestAccessor() => new TestAccessor(this); private struct ExportKey : IEquatable<ExportKey> { internal readonly string ExtensionTypeName; internal readonly string MetadataTypeName; public ExportKey(string extensionTypeName, string metadataTypeName) { this.ExtensionTypeName = extensionTypeName; this.MetadataTypeName = metadataTypeName; Hash.Combine(metadataTypeName.GetHashCode(), extensionTypeName.GetHashCode()); } public bool Equals(ExportKey other) { return string.Compare(this.ExtensionTypeName, other.ExtensionTypeName, StringComparison.OrdinalIgnoreCase) == 0 && string.Compare(this.MetadataTypeName, other.MetadataTypeName, StringComparison.OrdinalIgnoreCase) == 0; } public override bool Equals(object obj) => obj is ExportKey exportKey && this.Equals(exportKey); public override int GetHashCode() { return Hash.Combine(this.MetadataTypeName.GetHashCode(), this.ExtensionTypeName.GetHashCode()); } } internal readonly struct TestAccessor { #pragma warning disable IDE0052 // Remove unread private members - hold onto the services private readonly MefV1HostServices _mefV1HostServices; #pragma warning restore IDE0052 // Remove unread private members public TestAccessor(MefV1HostServices mefV1HostServices) { _mefV1HostServices = mefV1HostServices; } /// <summary> /// Injects replacement behavior for the <see cref="Create(IEnumerable{Assembly})"/> method. /// </summary> /// <param name="hook"></param> internal static void HookServiceCreation(CreationHook hook) { s_CreationHook = hook; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Collections.Immutable; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// A class that provides host services via classes instances exported via a MEF version 1 composition. /// </summary> public class MefV1HostServices : HostServices, IMefHostExportProvider { internal delegate MefV1HostServices CreationHook(IEnumerable<Assembly> assemblies); /// <summary> /// This delegate allows test code to override the behavior of <see cref="Create(IEnumerable{Assembly})"/>. /// </summary> /// <seealso cref="TestAccessor.HookServiceCreation"/> private static CreationHook s_CreationHook; // the export provider for the MEF composition private readonly ExportProvider _exportProvider; // accumulated cache for exports private ImmutableDictionary<ExportKey, IEnumerable> _exportsMap = ImmutableDictionary<ExportKey, IEnumerable>.Empty; private MefV1HostServices(ExportProvider exportProvider) { _exportProvider = exportProvider; } public static MefV1HostServices Create(ExportProvider exportProvider) { if (exportProvider == null) { throw new ArgumentNullException(nameof(exportProvider)); } return new MefV1HostServices(exportProvider); } public static MefV1HostServices Create(IEnumerable<Assembly> assemblies) { if (assemblies == null) { throw new ArgumentNullException(nameof(assemblies)); } if (s_CreationHook != null) { return s_CreationHook(assemblies); } var catalog = new AggregateCatalog(assemblies.Select(a => new AssemblyCatalog(a))); var container = new CompositionContainer(catalog, compositionOptions: CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe); return new MefV1HostServices(container); } /// <summary> /// Creates a new <see cref="HostWorkspaceServices"/> associated with the specified workspace. /// </summary> protected internal override HostWorkspaceServices CreateWorkspaceServices(Workspace workspace) { return new MefWorkspaceServices(this, workspace); } /// <summary> /// Gets all the MEF exports of the specified type with the specified metadata. /// </summary> public IEnumerable<Lazy<TExtension, TMetadata>> GetExports<TExtension, TMetadata>() { var key = new ExportKey(typeof(TExtension).AssemblyQualifiedName, typeof(TMetadata).AssemblyQualifiedName); if (!_exportsMap.TryGetValue(key, out var exports)) { exports = ImmutableInterlocked.GetOrAdd(ref _exportsMap, key, _ => { return _exportProvider.GetExports<TExtension, TMetadata>().ToImmutableArray(); }); } return (IEnumerable<Lazy<TExtension, TMetadata>>)exports; } /// <summary> /// Gets all the MEF exports of the specified type. /// </summary> public IEnumerable<Lazy<TExtension>> GetExports<TExtension>() { var key = new ExportKey(typeof(TExtension).AssemblyQualifiedName, ""); if (!_exportsMap.TryGetValue(key, out var exports)) { exports = ImmutableInterlocked.GetOrAdd(ref _exportsMap, key, _ => _exportProvider.GetExports<TExtension>().ToImmutableArray()); } return (IEnumerable<Lazy<TExtension>>)exports; } internal TestAccessor GetTestAccessor() => new TestAccessor(this); private struct ExportKey : IEquatable<ExportKey> { internal readonly string ExtensionTypeName; internal readonly string MetadataTypeName; public ExportKey(string extensionTypeName, string metadataTypeName) { this.ExtensionTypeName = extensionTypeName; this.MetadataTypeName = metadataTypeName; Hash.Combine(metadataTypeName.GetHashCode(), extensionTypeName.GetHashCode()); } public bool Equals(ExportKey other) { return string.Compare(this.ExtensionTypeName, other.ExtensionTypeName, StringComparison.OrdinalIgnoreCase) == 0 && string.Compare(this.MetadataTypeName, other.MetadataTypeName, StringComparison.OrdinalIgnoreCase) == 0; } public override bool Equals(object obj) => obj is ExportKey exportKey && this.Equals(exportKey); public override int GetHashCode() { return Hash.Combine(this.MetadataTypeName.GetHashCode(), this.ExtensionTypeName.GetHashCode()); } } internal readonly struct TestAccessor { #pragma warning disable IDE0052 // Remove unread private members - hold onto the services private readonly MefV1HostServices _mefV1HostServices; #pragma warning restore IDE0052 // Remove unread private members public TestAccessor(MefV1HostServices mefV1HostServices) { _mefV1HostServices = mefV1HostServices; } /// <summary> /// Injects replacement behavior for the <see cref="Create(IEnumerable{Assembly})"/> method. /// </summary> /// <param name="hook"></param> internal static void HookServiceCreation(CreationHook hook) { s_CreationHook = hook; } } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/UncheckedShortCircuit.txt
-=-=-=-=-=-=-=-=- SByte AndAlso SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.SByte,System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte AndAlso SByte => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) method: System.Nullable`1[System.SByte] op_Implicit(SByte) in System.Nullable`1[System.SByte] type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.SByte,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? AndAlso SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.SByte ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.Nullable`1[System.SByte],System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte AndAlso SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? AndAlso SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- E_SByte AndAlso E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) } return type: E_SByte type: System.Func`3[E_SByte,E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte AndAlso E_SByte => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) method: System.Nullable`1[E_SByte] op_Implicit(E_SByte) in System.Nullable`1[E_SByte] type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,E_SByte,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? AndAlso E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: E_SByte ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) } return type: E_SByte type: System.Func`3[System.Nullable`1[E_SByte],E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte AndAlso E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? AndAlso E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Byte AndAlso Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Byte,System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte AndAlso Byte => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) method: System.Nullable`1[System.Byte] op_Implicit(Byte) in System.Nullable`1[System.Byte] type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Byte,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? AndAlso Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Byte ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Nullable`1[System.Byte],System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte AndAlso Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? AndAlso Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- E_Byte AndAlso E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) } return type: E_Byte type: System.Func`3[E_Byte,E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte AndAlso E_Byte => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) method: System.Nullable`1[E_Byte] op_Implicit(E_Byte) in System.Nullable`1[E_Byte] type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,E_Byte,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? AndAlso E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: E_Byte ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) } return type: E_Byte type: System.Func`3[System.Nullable`1[E_Byte],E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte AndAlso E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? AndAlso E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Short AndAlso Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Int16,System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short AndAlso Short => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) method: System.Nullable`1[System.Int16] op_Implicit(Int16) in System.Nullable`1[System.Int16] type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Int16,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? AndAlso Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Int16 ) body { Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Nullable`1[System.Int16],System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short AndAlso Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? AndAlso Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- E_Short AndAlso E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[E_Short,E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short AndAlso E_Short => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) method: System.Nullable`1[E_Short] op_Implicit(E_Short) in System.Nullable`1[E_Short] type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,E_Short,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? AndAlso E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: E_Short ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[System.Nullable`1[E_Short],E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short AndAlso E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? AndAlso E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[System.Nullable`1[E_Short],System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- UShort AndAlso UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.UInt16,System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort AndAlso UShort => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) method: System.Nullable`1[System.UInt16] op_Implicit(UInt16) in System.Nullable`1[System.UInt16] type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.UInt16,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? AndAlso UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.UInt16 ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.Nullable`1[System.UInt16],System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort AndAlso UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? AndAlso UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- E_UShort AndAlso E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[E_UShort,E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort AndAlso E_UShort => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) method: System.Nullable`1[E_UShort] op_Implicit(E_UShort) in System.Nullable`1[E_UShort] type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,E_UShort,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? AndAlso E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: E_UShort ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[System.Nullable`1[E_UShort],E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort AndAlso E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? AndAlso E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Integer AndAlso Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Int32,System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer AndAlso Integer => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) method: System.Nullable`1[System.Int32] op_Implicit(Int32) in System.Nullable`1[System.Int32] type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Int32,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? AndAlso Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Int32 ) body { Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Nullable`1[System.Int32],System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer AndAlso Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? AndAlso Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- E_Integer AndAlso E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[E_Integer,E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer AndAlso E_Integer => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) method: System.Nullable`1[E_Integer] op_Implicit(E_Integer) in System.Nullable`1[E_Integer] type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,E_Integer,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? AndAlso E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: E_Integer ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[System.Nullable`1[E_Integer],E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer AndAlso E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? AndAlso E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- UInteger AndAlso UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.UInt32,System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger AndAlso UInteger => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) method: System.Nullable`1[System.UInt32] op_Implicit(UInt32) in System.Nullable`1[System.UInt32] type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.UInt32,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? AndAlso UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.UInt32 ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.Nullable`1[System.UInt32],System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger AndAlso UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? AndAlso UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- E_UInteger AndAlso E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[E_UInteger,E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger AndAlso E_UInteger => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) method: System.Nullable`1[E_UInteger] op_Implicit(E_UInteger) in System.Nullable`1[E_UInteger] type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,E_UInteger,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? AndAlso E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: E_UInteger ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[System.Nullable`1[E_UInteger],E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger AndAlso E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? AndAlso E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Long AndAlso Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Int64,System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long AndAlso Long => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Int64,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? AndAlso Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Int64 ) body { Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Nullable`1[System.Int64],System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long AndAlso Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? AndAlso Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- E_Long AndAlso E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[E_Long,E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long AndAlso E_Long => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) method: System.Nullable`1[E_Long] op_Implicit(E_Long) in System.Nullable`1[E_Long] type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,E_Long,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? AndAlso E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: E_Long ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[System.Nullable`1[E_Long],E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long AndAlso E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? AndAlso E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[System.Nullable`1[E_Long],System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- ULong AndAlso ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.UInt64,System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong AndAlso ULong => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) method: System.Nullable`1[System.UInt64] op_Implicit(UInt64) in System.Nullable`1[System.UInt64] type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.UInt64,System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? AndAlso ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.UInt64 ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.Nullable`1[System.UInt64],System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong AndAlso ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? AndAlso ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- E_ULong AndAlso E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[E_ULong,E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong AndAlso E_ULong => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) method: System.Nullable`1[E_ULong] op_Implicit(E_ULong) in System.Nullable`1[E_ULong] type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,E_ULong,System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? AndAlso E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: E_ULong ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[System.Nullable`1[E_ULong],E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong AndAlso E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? AndAlso E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Boolean AndAlso Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { AndAlso( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Boolean,System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean AndAlso Boolean => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Convert( AndAlso( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Boolean,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? AndAlso Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Boolean ) body { Convert( AndAlso( Parameter( x type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Nullable`1[System.Boolean],System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean AndAlso Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { AndAlso( Convert( Parameter( x type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? AndAlso Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { AndAlso( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Single AndAlso Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Single,System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single AndAlso Single => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Single ) type: System.Single ) method: System.Nullable`1[System.Single] op_Implicit(Single) in System.Nullable`1[System.Single] type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Single,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? AndAlso Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Single ) body { Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Nullable`1[System.Single],System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single AndAlso Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Nullable`1[System.Single] ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? AndAlso Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Nullable`1[System.Single] ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Nullable`1[System.Single],System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Double AndAlso Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Double,System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double AndAlso Double => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Double ) type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Double,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? AndAlso Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Double ) body { Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Nullable`1[System.Double],System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double AndAlso Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Nullable`1[System.Double] ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? AndAlso Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Nullable`1[System.Double],System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Decimal AndAlso Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( AndAlso( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Decimal,System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal AndAlso Decimal => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Convert( AndAlso( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) method: System.Nullable`1[System.Decimal] op_Implicit(System.Decimal) in System.Nullable`1[System.Decimal] type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Decimal,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? AndAlso Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Decimal ) body { Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Nullable`1[System.Decimal],System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal AndAlso Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( AndAlso( Convert( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? AndAlso Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- String AndAlso String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Convert( AndAlso( Convert( Parameter( x type: System.String ) method: Boolean ToBoolean(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) Convert( Parameter( y type: System.String ) method: Boolean ToBoolean(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object AndAlso Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { Convert( AndAlso( Convert( Parameter( x type: System.Object ) method: Boolean ToBoolean(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) Convert( Parameter( y type: System.Object ) method: Boolean ToBoolean(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) type: System.Boolean ) type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] ) -=-=-=-=-=-=-=-=- SByte OrElse SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.SByte,System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte OrElse SByte => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) method: System.Nullable`1[System.SByte] op_Implicit(SByte) in System.Nullable`1[System.SByte] type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.SByte,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? OrElse SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.SByte ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.Nullable`1[System.SByte],System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte OrElse SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? OrElse SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- E_SByte OrElse E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) } return type: E_SByte type: System.Func`3[E_SByte,E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte OrElse E_SByte => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) method: System.Nullable`1[E_SByte] op_Implicit(E_SByte) in System.Nullable`1[E_SByte] type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,E_SByte,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? OrElse E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: E_SByte ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) } return type: E_SByte type: System.Func`3[System.Nullable`1[E_SByte],E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte OrElse E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? OrElse E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Byte OrElse Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Byte,System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte OrElse Byte => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) method: System.Nullable`1[System.Byte] op_Implicit(Byte) in System.Nullable`1[System.Byte] type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Byte,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? OrElse Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Byte ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Nullable`1[System.Byte],System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte OrElse Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? OrElse Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- E_Byte OrElse E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) } return type: E_Byte type: System.Func`3[E_Byte,E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte OrElse E_Byte => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) method: System.Nullable`1[E_Byte] op_Implicit(E_Byte) in System.Nullable`1[E_Byte] type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,E_Byte,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? OrElse E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: E_Byte ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) } return type: E_Byte type: System.Func`3[System.Nullable`1[E_Byte],E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte OrElse E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? OrElse E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Short OrElse Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Int16,System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short OrElse Short => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) method: System.Nullable`1[System.Int16] op_Implicit(Int16) in System.Nullable`1[System.Int16] type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Int16,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? OrElse Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Int16 ) body { Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Nullable`1[System.Int16],System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short OrElse Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? OrElse Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- E_Short OrElse E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[E_Short,E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short OrElse E_Short => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) method: System.Nullable`1[E_Short] op_Implicit(E_Short) in System.Nullable`1[E_Short] type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,E_Short,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? OrElse E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: E_Short ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[System.Nullable`1[E_Short],E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short OrElse E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? OrElse E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[System.Nullable`1[E_Short],System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- UShort OrElse UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.UInt16,System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort OrElse UShort => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) method: System.Nullable`1[System.UInt16] op_Implicit(UInt16) in System.Nullable`1[System.UInt16] type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.UInt16,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? OrElse UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.UInt16 ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.Nullable`1[System.UInt16],System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort OrElse UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? OrElse UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- E_UShort OrElse E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[E_UShort,E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort OrElse E_UShort => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) method: System.Nullable`1[E_UShort] op_Implicit(E_UShort) in System.Nullable`1[E_UShort] type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,E_UShort,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? OrElse E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: E_UShort ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[System.Nullable`1[E_UShort],E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort OrElse E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? OrElse E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Integer OrElse Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Int32,System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer OrElse Integer => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) method: System.Nullable`1[System.Int32] op_Implicit(Int32) in System.Nullable`1[System.Int32] type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Int32,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? OrElse Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Int32 ) body { Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Nullable`1[System.Int32],System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer OrElse Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? OrElse Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- E_Integer OrElse E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[E_Integer,E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer OrElse E_Integer => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) method: System.Nullable`1[E_Integer] op_Implicit(E_Integer) in System.Nullable`1[E_Integer] type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,E_Integer,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? OrElse E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: E_Integer ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[System.Nullable`1[E_Integer],E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer OrElse E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? OrElse E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- UInteger OrElse UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.UInt32,System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger OrElse UInteger => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) method: System.Nullable`1[System.UInt32] op_Implicit(UInt32) in System.Nullable`1[System.UInt32] type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.UInt32,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? OrElse UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.UInt32 ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.Nullable`1[System.UInt32],System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger OrElse UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? OrElse UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- E_UInteger OrElse E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[E_UInteger,E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger OrElse E_UInteger => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) method: System.Nullable`1[E_UInteger] op_Implicit(E_UInteger) in System.Nullable`1[E_UInteger] type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,E_UInteger,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? OrElse E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: E_UInteger ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[System.Nullable`1[E_UInteger],E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger OrElse E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? OrElse E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Long OrElse Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Int64,System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long OrElse Long => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Int64,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? OrElse Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Int64 ) body { Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Nullable`1[System.Int64],System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long OrElse Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? OrElse Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- E_Long OrElse E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[E_Long,E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long OrElse E_Long => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) method: System.Nullable`1[E_Long] op_Implicit(E_Long) in System.Nullable`1[E_Long] type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,E_Long,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? OrElse E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: E_Long ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[System.Nullable`1[E_Long],E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long OrElse E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? OrElse E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[System.Nullable`1[E_Long],System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- ULong OrElse ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.UInt64,System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong OrElse ULong => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) method: System.Nullable`1[System.UInt64] op_Implicit(UInt64) in System.Nullable`1[System.UInt64] type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.UInt64,System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? OrElse ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.UInt64 ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.Nullable`1[System.UInt64],System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong OrElse ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? OrElse ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- E_ULong OrElse E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[E_ULong,E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong OrElse E_ULong => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) method: System.Nullable`1[E_ULong] op_Implicit(E_ULong) in System.Nullable`1[E_ULong] type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,E_ULong,System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? OrElse E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: E_ULong ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[System.Nullable`1[E_ULong],E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong OrElse E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? OrElse E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Boolean OrElse Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { OrElse( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Boolean,System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean OrElse Boolean => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Convert( OrElse( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Boolean,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? OrElse Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Boolean ) body { Convert( OrElse( Parameter( x type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Nullable`1[System.Boolean],System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean OrElse Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { OrElse( Convert( Parameter( x type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? OrElse Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { OrElse( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Single OrElse Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Single,System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single OrElse Single => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Single ) type: System.Single ) method: System.Nullable`1[System.Single] op_Implicit(Single) in System.Nullable`1[System.Single] type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Single,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? OrElse Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Single ) body { Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Nullable`1[System.Single],System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single OrElse Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Nullable`1[System.Single] ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? OrElse Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Nullable`1[System.Single] ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Nullable`1[System.Single],System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Double OrElse Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Double,System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double OrElse Double => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Double ) type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Double,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? OrElse Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Double ) body { Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Nullable`1[System.Double],System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double OrElse Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Nullable`1[System.Double] ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? OrElse Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Nullable`1[System.Double],System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Decimal OrElse Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( OrElse( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Decimal,System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal OrElse Decimal => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Convert( OrElse( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) method: System.Nullable`1[System.Decimal] op_Implicit(System.Decimal) in System.Nullable`1[System.Decimal] type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Decimal,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? OrElse Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Decimal ) body { Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Nullable`1[System.Decimal],System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal OrElse Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( OrElse( Convert( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? OrElse Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- String OrElse String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Convert( OrElse( Convert( Parameter( x type: System.String ) method: Boolean ToBoolean(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) Convert( Parameter( y type: System.String ) method: Boolean ToBoolean(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object OrElse Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { Convert( OrElse( Convert( Parameter( x type: System.Object ) method: Boolean ToBoolean(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) Convert( Parameter( y type: System.Object ) method: Boolean ToBoolean(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) type: System.Boolean ) type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] )
-=-=-=-=-=-=-=-=- SByte AndAlso SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.SByte,System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte AndAlso SByte => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) method: System.Nullable`1[System.SByte] op_Implicit(SByte) in System.Nullable`1[System.SByte] type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.SByte,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? AndAlso SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.SByte ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.Nullable`1[System.SByte],System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte AndAlso SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? AndAlso SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- E_SByte AndAlso E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) } return type: E_SByte type: System.Func`3[E_SByte,E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte AndAlso E_SByte => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) method: System.Nullable`1[E_SByte] op_Implicit(E_SByte) in System.Nullable`1[E_SByte] type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,E_SByte,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? AndAlso E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: E_SByte ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) } return type: E_SByte type: System.Func`3[System.Nullable`1[E_SByte],E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte AndAlso E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? AndAlso E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Byte AndAlso Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Byte,System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte AndAlso Byte => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) method: System.Nullable`1[System.Byte] op_Implicit(Byte) in System.Nullable`1[System.Byte] type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Byte,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? AndAlso Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Byte ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Nullable`1[System.Byte],System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte AndAlso Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? AndAlso Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- E_Byte AndAlso E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) } return type: E_Byte type: System.Func`3[E_Byte,E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte AndAlso E_Byte => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) method: System.Nullable`1[E_Byte] op_Implicit(E_Byte) in System.Nullable`1[E_Byte] type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,E_Byte,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? AndAlso E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: E_Byte ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) } return type: E_Byte type: System.Func`3[System.Nullable`1[E_Byte],E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte AndAlso E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? AndAlso E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Short AndAlso Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Int16,System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short AndAlso Short => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) method: System.Nullable`1[System.Int16] op_Implicit(Int16) in System.Nullable`1[System.Int16] type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Int16,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? AndAlso Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Int16 ) body { Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Nullable`1[System.Int16],System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short AndAlso Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? AndAlso Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- E_Short AndAlso E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[E_Short,E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short AndAlso E_Short => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) method: System.Nullable`1[E_Short] op_Implicit(E_Short) in System.Nullable`1[E_Short] type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,E_Short,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? AndAlso E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: E_Short ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[System.Nullable`1[E_Short],E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short AndAlso E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? AndAlso E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[System.Nullable`1[E_Short],System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- UShort AndAlso UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.UInt16,System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort AndAlso UShort => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) method: System.Nullable`1[System.UInt16] op_Implicit(UInt16) in System.Nullable`1[System.UInt16] type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.UInt16,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? AndAlso UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.UInt16 ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.Nullable`1[System.UInt16],System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort AndAlso UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? AndAlso UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- E_UShort AndAlso E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[E_UShort,E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort AndAlso E_UShort => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) method: System.Nullable`1[E_UShort] op_Implicit(E_UShort) in System.Nullable`1[E_UShort] type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,E_UShort,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? AndAlso E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: E_UShort ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[System.Nullable`1[E_UShort],E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort AndAlso E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? AndAlso E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Integer AndAlso Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Int32,System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer AndAlso Integer => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) method: System.Nullable`1[System.Int32] op_Implicit(Int32) in System.Nullable`1[System.Int32] type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Int32,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? AndAlso Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Int32 ) body { Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Nullable`1[System.Int32],System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer AndAlso Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? AndAlso Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- E_Integer AndAlso E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[E_Integer,E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer AndAlso E_Integer => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) method: System.Nullable`1[E_Integer] op_Implicit(E_Integer) in System.Nullable`1[E_Integer] type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,E_Integer,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? AndAlso E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: E_Integer ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[System.Nullable`1[E_Integer],E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer AndAlso E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? AndAlso E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- UInteger AndAlso UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.UInt32,System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger AndAlso UInteger => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) method: System.Nullable`1[System.UInt32] op_Implicit(UInt32) in System.Nullable`1[System.UInt32] type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.UInt32,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? AndAlso UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.UInt32 ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.Nullable`1[System.UInt32],System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger AndAlso UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? AndAlso UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- E_UInteger AndAlso E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[E_UInteger,E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger AndAlso E_UInteger => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) method: System.Nullable`1[E_UInteger] op_Implicit(E_UInteger) in System.Nullable`1[E_UInteger] type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,E_UInteger,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? AndAlso E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: E_UInteger ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[System.Nullable`1[E_UInteger],E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger AndAlso E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? AndAlso E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Long AndAlso Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Int64,System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long AndAlso Long => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Int64,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? AndAlso Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Int64 ) body { Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Nullable`1[System.Int64],System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long AndAlso Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? AndAlso Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- E_Long AndAlso E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[E_Long,E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long AndAlso E_Long => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) method: System.Nullable`1[E_Long] op_Implicit(E_Long) in System.Nullable`1[E_Long] type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,E_Long,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? AndAlso E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: E_Long ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[System.Nullable`1[E_Long],E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long AndAlso E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? AndAlso E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[System.Nullable`1[E_Long],System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- ULong AndAlso ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.UInt64,System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong AndAlso ULong => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) method: System.Nullable`1[System.UInt64] op_Implicit(UInt64) in System.Nullable`1[System.UInt64] type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.UInt64,System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? AndAlso ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.UInt64 ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.Nullable`1[System.UInt64],System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong AndAlso ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? AndAlso ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- E_ULong AndAlso E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[E_ULong,E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong AndAlso E_ULong => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) method: System.Nullable`1[E_ULong] op_Implicit(E_ULong) in System.Nullable`1[E_ULong] type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,E_ULong,System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? AndAlso E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: E_ULong ) body { Convert( Negate( Convert( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[System.Nullable`1[E_ULong],E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong AndAlso E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? AndAlso E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Boolean AndAlso Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { AndAlso( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Boolean,System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean AndAlso Boolean => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Convert( AndAlso( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Boolean,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? AndAlso Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Boolean ) body { Convert( AndAlso( Parameter( x type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Nullable`1[System.Boolean],System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean AndAlso Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { AndAlso( Convert( Parameter( x type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? AndAlso Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { AndAlso( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Single AndAlso Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Single,System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single AndAlso Single => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Single ) type: System.Single ) method: System.Nullable`1[System.Single] op_Implicit(Single) in System.Nullable`1[System.Single] type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Single,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? AndAlso Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Single ) body { Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Nullable`1[System.Single],System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single AndAlso Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Nullable`1[System.Single] ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? AndAlso Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Nullable`1[System.Single] ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Nullable`1[System.Single],System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Double AndAlso Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Double,System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double AndAlso Double => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Negate( Convert( AndAlso( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Double ) type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Double,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? AndAlso Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Double ) body { Negate( Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Nullable`1[System.Double],System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double AndAlso Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Nullable`1[System.Double] ) body { Negate( Convert( AndAlso( Convert( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? AndAlso Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) body { Negate( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Nullable`1[System.Double],System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Decimal AndAlso Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( AndAlso( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Decimal,System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal AndAlso Decimal => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Convert( AndAlso( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) method: System.Nullable`1[System.Decimal] op_Implicit(System.Decimal) in System.Nullable`1[System.Decimal] type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Decimal,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? AndAlso Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Decimal ) body { Convert( Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Nullable`1[System.Decimal],System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal AndAlso Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( AndAlso( Convert( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? AndAlso Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( AndAlso( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- String AndAlso String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Convert( AndAlso( Convert( Parameter( x type: System.String ) method: Boolean ToBoolean(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) Convert( Parameter( y type: System.String ) method: Boolean ToBoolean(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object AndAlso Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { Convert( AndAlso( Convert( Parameter( x type: System.Object ) method: Boolean ToBoolean(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) Convert( Parameter( y type: System.Object ) method: Boolean ToBoolean(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) type: System.Boolean ) type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] ) -=-=-=-=-=-=-=-=- SByte OrElse SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.SByte,System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte OrElse SByte => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.SByte ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) method: System.Nullable`1[System.SByte] op_Implicit(SByte) in System.Nullable`1[System.SByte] type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.SByte,System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? OrElse SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.SByte ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`3[System.Nullable`1[System.SByte],System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- SByte OrElse SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.SByte,System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- SByte? OrElse SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`3[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- E_SByte OrElse E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) } return type: E_SByte type: System.Func`3[E_SByte,E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte OrElse E_SByte => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: E_SByte ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) method: System.Nullable`1[E_SByte] op_Implicit(E_SByte) in System.Nullable`1[E_SByte] type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,E_SByte,System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? OrElse E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: E_SByte ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_SByte ) } return type: E_SByte type: System.Func`3[System.Nullable`1[E_SByte],E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- E_SByte OrElse E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_SByte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[E_SByte,System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- E_SByte? OrElse E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`3[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Byte OrElse Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Byte,System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte OrElse Byte => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Byte ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) method: System.Nullable`1[System.Byte] op_Implicit(Byte) in System.Nullable`1[System.Byte] type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Byte,System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? OrElse Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Byte ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`3[System.Nullable`1[System.Byte],System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Byte OrElse Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Byte,System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Byte? OrElse Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`3[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- E_Byte OrElse E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) } return type: E_Byte type: System.Func`3[E_Byte,E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte OrElse E_Byte => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: E_Byte ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) method: System.Nullable`1[E_Byte] op_Implicit(E_Byte) in System.Nullable`1[E_Byte] type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,E_Byte,System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? OrElse E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: E_Byte ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Byte ) } return type: E_Byte type: System.Func`3[System.Nullable`1[E_Byte],E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- E_Byte OrElse E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_Byte ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[E_Byte,System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- E_Byte? OrElse E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`3[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Short OrElse Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Int16,System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short OrElse Short => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Int16 ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) method: System.Nullable`1[System.Int16] op_Implicit(Int16) in System.Nullable`1[System.Int16] type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Int16,System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? OrElse Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Int16 ) body { Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`3[System.Nullable`1[System.Int16],System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Short OrElse Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Int16,System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Short? OrElse Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`3[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- E_Short OrElse E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[E_Short,E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short OrElse E_Short => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: E_Short ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) method: System.Nullable`1[E_Short] op_Implicit(E_Short) in System.Nullable`1[E_Short] type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,E_Short,System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? OrElse E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: E_Short ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`3[System.Nullable`1[E_Short],E_Short,E_Short] ) -=-=-=-=-=-=-=-=- E_Short OrElse E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_Short ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[E_Short,System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- E_Short? OrElse E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`3[System.Nullable`1[E_Short],System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- UShort OrElse UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.UInt16,System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort OrElse UShort => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.UInt16 ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) method: System.Nullable`1[System.UInt16] op_Implicit(UInt16) in System.Nullable`1[System.UInt16] type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.UInt16,System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? OrElse UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.UInt16 ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`3[System.Nullable`1[System.UInt16],System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- UShort OrElse UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.UInt16,System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- UShort? OrElse UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`3[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- E_UShort OrElse E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[E_UShort,E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort OrElse E_UShort => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: E_UShort ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) method: System.Nullable`1[E_UShort] op_Implicit(E_UShort) in System.Nullable`1[E_UShort] type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,E_UShort,System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? OrElse E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: E_UShort ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: E_UShort ) } return type: E_UShort type: System.Func`3[System.Nullable`1[E_UShort],E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- E_UShort OrElse E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[E_UShort,System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- E_UShort? OrElse E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int16 ) type: System.Int16 ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`3[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Integer OrElse Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Int32,System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer OrElse Integer => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Int32 ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) method: System.Nullable`1[System.Int32] op_Implicit(Int32) in System.Nullable`1[System.Int32] type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Int32,System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? OrElse Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Int32 ) body { Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`3[System.Nullable`1[System.Int32],System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Integer OrElse Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Int32,System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Integer? OrElse Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`3[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- E_Integer OrElse E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[E_Integer,E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer OrElse E_Integer => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: E_Integer ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) method: System.Nullable`1[E_Integer] op_Implicit(E_Integer) in System.Nullable`1[E_Integer] type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,E_Integer,System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? OrElse E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: E_Integer ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`3[System.Nullable`1[E_Integer],E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- E_Integer OrElse E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[E_Integer,System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- E_Integer? OrElse E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`3[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- UInteger OrElse UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.UInt32,System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger OrElse UInteger => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.UInt32 ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) method: System.Nullable`1[System.UInt32] op_Implicit(UInt32) in System.Nullable`1[System.UInt32] type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.UInt32,System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? OrElse UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.UInt32 ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`3[System.Nullable`1[System.UInt32],System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- UInteger OrElse UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.UInt32,System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- UInteger? OrElse UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`3[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- E_UInteger OrElse E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[E_UInteger,E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger OrElse E_UInteger => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: E_UInteger ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) method: System.Nullable`1[E_UInteger] op_Implicit(E_UInteger) in System.Nullable`1[E_UInteger] type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,E_UInteger,System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? OrElse E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: E_UInteger ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int32 ) type: System.Int32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`3[System.Nullable`1[E_UInteger],E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- E_UInteger OrElse E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: Boolean ToBoolean(UInt32) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[E_UInteger,System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- E_UInteger? OrElse E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt32) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int32 ) type: System.Int32 ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`3[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Long OrElse Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Int64,System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long OrElse Long => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Int64 ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) method: System.Nullable`1[System.Int64] op_Implicit(Int64) in System.Nullable`1[System.Int64] type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Int64,System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? OrElse Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Int64 ) body { Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`3[System.Nullable`1[System.Int64],System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Long OrElse Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Int64,System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Long? OrElse Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`3[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- E_Long OrElse E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[E_Long,E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long OrElse E_Long => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: E_Long ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) method: System.Nullable`1[E_Long] op_Implicit(E_Long) in System.Nullable`1[E_Long] type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,E_Long,System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? OrElse E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: E_Long ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`3[System.Nullable`1[E_Long],E_Long,E_Long] ) -=-=-=-=-=-=-=-=- E_Long OrElse E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) method: Boolean ToBoolean(Int64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[E_Long,System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- E_Long? OrElse E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: Boolean ToBoolean(Int64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`3[System.Nullable`1[E_Long],System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- ULong OrElse ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.UInt64,System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong OrElse ULong => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.UInt64 ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) method: System.Nullable`1[System.UInt64] op_Implicit(UInt64) in System.Nullable`1[System.UInt64] type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.UInt64,System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? OrElse ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.UInt64 ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`3[System.Nullable`1[System.UInt64],System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- ULong OrElse ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.UInt64,System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- ULong? OrElse ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) Parameter( y type: System.Nullable`1[System.UInt64] ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`3[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- E_ULong OrElse E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[E_ULong,E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong OrElse E_ULong => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: E_ULong ) body { Convert( Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) method: System.Nullable`1[E_ULong] op_Implicit(E_ULong) in System.Nullable`1[E_ULong] type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,E_ULong,System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? OrElse E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: E_ULong ) body { Convert( Negate( Convert( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Convert( Parameter( y type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Int64 ) type: System.Int64 ) type: E_ULong ) } return type: E_ULong type: System.Func`3[System.Nullable`1[E_ULong],E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- E_ULong OrElse E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: Boolean ToBoolean(UInt64) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[E_ULong,System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- E_ULong? OrElse E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) Parameter( y type: System.Nullable`1[E_ULong] ) body { Convert( Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: Boolean ToBoolean(UInt64) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Int64 ) type: System.Int64 ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`3[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Boolean OrElse Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { OrElse( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Boolean,System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean OrElse Boolean => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) body { Convert( OrElse( Parameter( x type: System.Boolean ) Parameter( y type: System.Boolean ) type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Boolean,System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? OrElse Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Boolean ) body { Convert( OrElse( Parameter( x type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted type: System.Boolean ) } return type: System.Boolean type: System.Func`3[System.Nullable`1[System.Boolean],System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Boolean OrElse Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { OrElse( Convert( Parameter( x type: System.Boolean ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Boolean,System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Boolean? OrElse Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { OrElse( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`3[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Single OrElse Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Single,System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single OrElse Single => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Single ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Single ) type: System.Single ) method: System.Nullable`1[System.Single] op_Implicit(Single) in System.Nullable`1[System.Single] type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Single,System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? OrElse Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Single ) body { Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`3[System.Nullable`1[System.Single],System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Single OrElse Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.Nullable`1[System.Single] ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Single ) method: Boolean ToBoolean(Single) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Single,System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Single? OrElse Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.Nullable`1[System.Single] ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Boolean ToBoolean(Single) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`3[System.Nullable`1[System.Single],System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Double OrElse Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Double,System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double OrElse Double => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Double ) body { Convert( Negate( Convert( OrElse( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) type: System.Boolean ) type: System.Double ) type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Double,System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? OrElse Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Double ) body { Negate( Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`3[System.Nullable`1[System.Double],System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Double OrElse Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.Nullable`1[System.Double] ) body { Negate( Convert( OrElse( Convert( Convert( Parameter( x type: System.Double ) method: Boolean ToBoolean(Double) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Double,System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Double? OrElse Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) body { Negate( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Boolean ToBoolean(Double) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`3[System.Nullable`1[System.Double],System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Decimal OrElse Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( OrElse( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Decimal,System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal OrElse Decimal => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Decimal ) body { Convert( Convert( OrElse( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) method: System.Nullable`1[System.Decimal] op_Implicit(System.Decimal) in System.Nullable`1[System.Decimal] type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Decimal,System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? OrElse Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Decimal ) body { Convert( Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Convert( Parameter( y type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Decimal ) } return type: System.Decimal type: System.Func`3[System.Nullable`1[System.Decimal],System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Decimal OrElse Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( OrElse( Convert( Convert( Parameter( x type: System.Decimal ) method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Boolean ) method: System.Nullable`1[System.Boolean] op_Implicit(Boolean) in System.Nullable`1[System.Boolean] type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Decimal,System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Decimal? OrElse Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( OrElse( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Convert( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Boolean ToBoolean(System.Decimal) in System.Convert type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull method: System.Decimal ToDecimal(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`3[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- String OrElse String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Convert( OrElse( Convert( Parameter( x type: System.String ) method: Boolean ToBoolean(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) Convert( Parameter( y type: System.String ) method: Boolean ToBoolean(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object OrElse Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { Convert( OrElse( Convert( Parameter( x type: System.Object ) method: Boolean ToBoolean(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) Convert( Parameter( y type: System.Object ) method: Boolean ToBoolean(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Boolean ) type: System.Boolean ) type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] )
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TreeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// this provides information about the syntax tree formatting service is formatting. /// this provides necessary abstraction between different kinds of syntax trees so that ones that contain /// actual text or cache can answer queries more efficiently. /// </summary> internal abstract partial class TreeData { public static TreeData Create(SyntaxNode root) { // either there is no tree or a tree that is not generated from a text. if (root.SyntaxTree == null || !root.SyntaxTree.TryGetText(out var text)) { return new Node(root); } #if DEBUG return new Debug(root, text); #else return new NodeAndText(root, text); #endif } public static TreeData Create(SyntaxTrivia trivia, int initialColumn) => new StructuredTrivia(trivia, initialColumn); private readonly SyntaxNode _root; private readonly SyntaxToken _firstToken; private readonly SyntaxToken _lastToken; public TreeData(SyntaxNode root) { Contract.ThrowIfNull(root); _root = root; _firstToken = _root.GetFirstToken(includeZeroWidth: true); _lastToken = _root.GetLastToken(includeZeroWidth: true); } public abstract string GetTextBetween(SyntaxToken token1, SyntaxToken token2); public abstract int GetOriginalColumn(int tabSize, SyntaxToken token); public SyntaxNode Root => _root; public bool IsFirstToken(SyntaxToken token) => _firstToken == token; public bool IsLastToken(SyntaxToken token) => _lastToken == token; public int StartPosition { get { return this.Root.FullSpan.Start; } } public int EndPosition { get { return this.Root.FullSpan.End; } } public IEnumerable<SyntaxToken> GetApplicableTokens(TextSpan textSpan) => this.Root.DescendantTokens(textSpan); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// this provides information about the syntax tree formatting service is formatting. /// this provides necessary abstraction between different kinds of syntax trees so that ones that contain /// actual text or cache can answer queries more efficiently. /// </summary> internal abstract partial class TreeData { public static TreeData Create(SyntaxNode root) { // either there is no tree or a tree that is not generated from a text. if (root.SyntaxTree == null || !root.SyntaxTree.TryGetText(out var text)) { return new Node(root); } #if DEBUG return new Debug(root, text); #else return new NodeAndText(root, text); #endif } public static TreeData Create(SyntaxTrivia trivia, int initialColumn) => new StructuredTrivia(trivia, initialColumn); private readonly SyntaxNode _root; private readonly SyntaxToken _firstToken; private readonly SyntaxToken _lastToken; public TreeData(SyntaxNode root) { Contract.ThrowIfNull(root); _root = root; _firstToken = _root.GetFirstToken(includeZeroWidth: true); _lastToken = _root.GetLastToken(includeZeroWidth: true); } public abstract string GetTextBetween(SyntaxToken token1, SyntaxToken token2); public abstract int GetOriginalColumn(int tabSize, SyntaxToken token); public SyntaxNode Root => _root; public bool IsFirstToken(SyntaxToken token) => _firstToken == token; public bool IsLastToken(SyntaxToken token) => _lastToken == token; public int StartPosition { get { return this.Root.FullSpan.Start; } } public int EndPosition { get { return this.Root.FullSpan.End; } } public IEnumerable<SyntaxToken> GetApplicableTokens(TextSpan textSpan) => this.Root.DescendantTokens(textSpan); } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.ExpressionSyntaxGeneratorVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal partial class ITypeSymbolExtensions { private class ExpressionSyntaxGeneratorVisitor : SymbolVisitor<ExpressionSyntax> { public static readonly ExpressionSyntaxGeneratorVisitor Instance = new(); private ExpressionSyntaxGeneratorVisitor() { } public override ExpressionSyntax DefaultVisit(ISymbol symbol) => symbol.Accept(TypeSyntaxGeneratorVisitor.Create())!; private static TExpressionSyntax AddInformationTo<TExpressionSyntax>(TExpressionSyntax syntax, ISymbol symbol) where TExpressionSyntax : ExpressionSyntax { syntax = syntax.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker); syntax = syntax.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol)); return syntax; } public override ExpressionSyntax VisitNamedType(INamedTypeSymbol symbol) { if (TypeSyntaxGeneratorVisitor.TryCreateNativeIntegerType(symbol, out var typeSyntax)) return typeSyntax; typeSyntax = TypeSyntaxGeneratorVisitor.Create().CreateSimpleTypeSyntax(symbol); if (!(typeSyntax is SimpleNameSyntax)) return typeSyntax; var simpleNameSyntax = (SimpleNameSyntax)typeSyntax; if (symbol.ContainingType != null) { if (symbol.ContainingType.TypeKind == TypeKind.Submission) { return simpleNameSyntax; } else { var container = symbol.ContainingType.Accept(this)!; return CreateMemberAccessExpression(symbol, container, simpleNameSyntax); } } else if (symbol.ContainingNamespace != null) { if (symbol.ContainingNamespace.IsGlobalNamespace) { if (symbol.TypeKind != TypeKind.Error) { return AddInformationTo( SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), simpleNameSyntax), symbol); } } else { var container = symbol.ContainingNamespace.Accept(this)!; return CreateMemberAccessExpression(symbol, container, simpleNameSyntax); } } return simpleNameSyntax; } public override ExpressionSyntax VisitNamespace(INamespaceSymbol symbol) { var syntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol); if (symbol.ContainingNamespace == null) { return syntax; } if (symbol.ContainingNamespace.IsGlobalNamespace) { return AddInformationTo( SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), syntax), symbol); } else { var container = symbol.ContainingNamespace.Accept(this)!; return CreateMemberAccessExpression(symbol, container, syntax); } } private static ExpressionSyntax CreateMemberAccessExpression( ISymbol symbol, ExpressionSyntax container, SimpleNameSyntax syntax) { return AddInformationTo(SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, container, syntax), symbol); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal partial class ITypeSymbolExtensions { private class ExpressionSyntaxGeneratorVisitor : SymbolVisitor<ExpressionSyntax> { public static readonly ExpressionSyntaxGeneratorVisitor Instance = new(); private ExpressionSyntaxGeneratorVisitor() { } public override ExpressionSyntax DefaultVisit(ISymbol symbol) => symbol.Accept(TypeSyntaxGeneratorVisitor.Create())!; private static TExpressionSyntax AddInformationTo<TExpressionSyntax>(TExpressionSyntax syntax, ISymbol symbol) where TExpressionSyntax : ExpressionSyntax { syntax = syntax.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker); syntax = syntax.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol)); return syntax; } public override ExpressionSyntax VisitNamedType(INamedTypeSymbol symbol) { if (TypeSyntaxGeneratorVisitor.TryCreateNativeIntegerType(symbol, out var typeSyntax)) return typeSyntax; typeSyntax = TypeSyntaxGeneratorVisitor.Create().CreateSimpleTypeSyntax(symbol); if (!(typeSyntax is SimpleNameSyntax)) return typeSyntax; var simpleNameSyntax = (SimpleNameSyntax)typeSyntax; if (symbol.ContainingType != null) { if (symbol.ContainingType.TypeKind == TypeKind.Submission) { return simpleNameSyntax; } else { var container = symbol.ContainingType.Accept(this)!; return CreateMemberAccessExpression(symbol, container, simpleNameSyntax); } } else if (symbol.ContainingNamespace != null) { if (symbol.ContainingNamespace.IsGlobalNamespace) { if (symbol.TypeKind != TypeKind.Error) { return AddInformationTo( SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), simpleNameSyntax), symbol); } } else { var container = symbol.ContainingNamespace.Accept(this)!; return CreateMemberAccessExpression(symbol, container, simpleNameSyntax); } } return simpleNameSyntax; } public override ExpressionSyntax VisitNamespace(INamespaceSymbol symbol) { var syntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol); if (symbol.ContainingNamespace == null) { return syntax; } if (symbol.ContainingNamespace.IsGlobalNamespace) { return AddInformationTo( SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), syntax), symbol); } else { var container = symbol.ContainingNamespace.Accept(this)!; return CreateMemberAccessExpression(symbol, container, syntax); } } private static ExpressionSyntax CreateMemberAccessExpression( ISymbol symbol, ExpressionSyntax container, SimpleNameSyntax syntax) { return AddInformationTo(SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, container, syntax), symbol); } } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/EditorFeatures/CSharpTest/Formatting/FormattingAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { public class FormattingAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public FormattingAnalyzerTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new FormattingDiagnosticAnalyzer(), new FormattingCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task TrailingWhitespace() { var testCode = "class X[| |]" + Environment.NewLine + "{" + Environment.NewLine + "}" + Environment.NewLine; var expected = "class X" + Environment.NewLine + "{" + Environment.NewLine + "}" + Environment.NewLine; await TestInRegularAndScriptAsync(testCode, expected); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task TestMissingSpace() { var testCode = @" class TypeName { void Method() { if$$(true)return; } } "; var expected = @" class TypeName { void Method() { if (true) return; } } "; await TestInRegularAndScriptAsync(testCode, expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { public class FormattingAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public FormattingAnalyzerTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new FormattingDiagnosticAnalyzer(), new FormattingCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task TrailingWhitespace() { var testCode = "class X[| |]" + Environment.NewLine + "{" + Environment.NewLine + "}" + Environment.NewLine; var expected = "class X" + Environment.NewLine + "{" + Environment.NewLine + "}" + Environment.NewLine; await TestInRegularAndScriptAsync(testCode, expected); } [Fact, Trait(Traits.Feature, Traits.Features.Formatting)] public async Task TestMissingSpace() { var testCode = @" class TypeName { void Method() { if$$(true)return; } } "; var expected = @" class TypeName { void Method() { if (true) return; } } "; await TestInRegularAndScriptAsync(testCode, expected); } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Field.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitFieldAccess(BoundFieldAccess node) { BoundExpression? rewrittenReceiver = VisitExpression(node.ReceiverOpt); return MakeFieldAccess(node.Syntax, rewrittenReceiver, node.FieldSymbol, node.ConstantValue, node.ResultKind, node.Type, node); } private BoundExpression MakeFieldAccess( SyntaxNode syntax, BoundExpression? rewrittenReceiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol type, BoundFieldAccess? oldNodeOpt = null) { if (fieldSymbol.ContainingType.IsTupleType) { return MakeTupleFieldAccess(syntax, fieldSymbol, rewrittenReceiver); } BoundExpression result = oldNodeOpt != null ? oldNodeOpt.Update(rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type) : new BoundFieldAccess(syntax, rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type); if (fieldSymbol.IsFixedSizeBuffer) { // a reference to a fixed buffer is translated into its address result = new BoundAddressOfOperator(syntax, result, type, false); } return result; } /// <summary> /// Converts access to a tuple instance into access into the underlying ValueTuple(s). /// /// For instance, tuple.Item8 /// produces fieldAccess(field=Item1, receiver=fieldAccess(field=Rest, receiver=ValueTuple for tuple)) /// </summary> private BoundExpression MakeTupleFieldAccess( SyntaxNode syntax, FieldSymbol tupleField, BoundExpression? rewrittenReceiver) { var tupleType = tupleField.ContainingType; NamedTypeSymbol currentLinkType = tupleType; FieldSymbol underlyingField = tupleField.TupleUnderlyingField; if ((object)underlyingField == null) { // Use-site error must have been reported elsewhere. return _factory.BadExpression(tupleField.Type); } if (rewrittenReceiver?.Kind == BoundKind.DefaultExpression) { // Optimization: `default((int, string)).Item2` is simply `default(string)` return new BoundDefaultExpression(syntax, tupleField.Type); } if (!TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything2)) { WellKnownMember wellKnownTupleRest = NamedTypeSymbol.GetTupleTypeMember(NamedTypeSymbol.ValueTupleRestPosition, NamedTypeSymbol.ValueTupleRestPosition); var tupleRestField = (FieldSymbol?)NamedTypeSymbol.GetWellKnownMemberInType(currentLinkType.OriginalDefinition, wellKnownTupleRest, _diagnostics, syntax); if (tupleRestField is null) { // error tolerance for cases when Rest is missing return _factory.BadExpression(tupleField.Type); } // make nested field accesses to Rest do { FieldSymbol nestedFieldSymbol = tupleRestField.AsMember(currentLinkType); rewrittenReceiver = _factory.Field(rewrittenReceiver, nestedFieldSymbol); currentLinkType = (NamedTypeSymbol)currentLinkType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[NamedTypeSymbol.ValueTupleRestPosition - 1].Type; } while (!TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything2)); } // make a field access for the most local access return _factory.Field(rewrittenReceiver, underlyingField); } private BoundExpression MakeTupleFieldAccessAndReportUseSiteDiagnostics(BoundExpression tuple, SyntaxNode syntax, FieldSymbol field) { // Use default field rather than implicitly named fields since // fields from inferred names are not usable in C# 7.0. field = field.CorrespondingTupleField ?? field; UseSiteInfo<AssemblySymbol> useSiteInfo = field.GetUseSiteInfo(); if (useSiteInfo.DiagnosticInfo?.Severity != DiagnosticSeverity.Error) { useSiteInfo = useSiteInfo.AdjustDiagnosticInfo(null); } _diagnostics.Add(useSiteInfo, syntax.Location); return MakeTupleFieldAccess(syntax, field, tuple); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitFieldAccess(BoundFieldAccess node) { BoundExpression? rewrittenReceiver = VisitExpression(node.ReceiverOpt); return MakeFieldAccess(node.Syntax, rewrittenReceiver, node.FieldSymbol, node.ConstantValue, node.ResultKind, node.Type, node); } private BoundExpression MakeFieldAccess( SyntaxNode syntax, BoundExpression? rewrittenReceiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol type, BoundFieldAccess? oldNodeOpt = null) { if (fieldSymbol.ContainingType.IsTupleType) { return MakeTupleFieldAccess(syntax, fieldSymbol, rewrittenReceiver); } BoundExpression result = oldNodeOpt != null ? oldNodeOpt.Update(rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type) : new BoundFieldAccess(syntax, rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type); if (fieldSymbol.IsFixedSizeBuffer) { // a reference to a fixed buffer is translated into its address result = new BoundAddressOfOperator(syntax, result, type, false); } return result; } /// <summary> /// Converts access to a tuple instance into access into the underlying ValueTuple(s). /// /// For instance, tuple.Item8 /// produces fieldAccess(field=Item1, receiver=fieldAccess(field=Rest, receiver=ValueTuple for tuple)) /// </summary> private BoundExpression MakeTupleFieldAccess( SyntaxNode syntax, FieldSymbol tupleField, BoundExpression? rewrittenReceiver) { var tupleType = tupleField.ContainingType; NamedTypeSymbol currentLinkType = tupleType; FieldSymbol underlyingField = tupleField.TupleUnderlyingField; if ((object)underlyingField == null) { // Use-site error must have been reported elsewhere. return _factory.BadExpression(tupleField.Type); } if (rewrittenReceiver?.Kind == BoundKind.DefaultExpression) { // Optimization: `default((int, string)).Item2` is simply `default(string)` return new BoundDefaultExpression(syntax, tupleField.Type); } if (!TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything2)) { WellKnownMember wellKnownTupleRest = NamedTypeSymbol.GetTupleTypeMember(NamedTypeSymbol.ValueTupleRestPosition, NamedTypeSymbol.ValueTupleRestPosition); var tupleRestField = (FieldSymbol?)NamedTypeSymbol.GetWellKnownMemberInType(currentLinkType.OriginalDefinition, wellKnownTupleRest, _diagnostics, syntax); if (tupleRestField is null) { // error tolerance for cases when Rest is missing return _factory.BadExpression(tupleField.Type); } // make nested field accesses to Rest do { FieldSymbol nestedFieldSymbol = tupleRestField.AsMember(currentLinkType); rewrittenReceiver = _factory.Field(rewrittenReceiver, nestedFieldSymbol); currentLinkType = (NamedTypeSymbol)currentLinkType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[NamedTypeSymbol.ValueTupleRestPosition - 1].Type; } while (!TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything2)); } // make a field access for the most local access return _factory.Field(rewrittenReceiver, underlyingField); } private BoundExpression MakeTupleFieldAccessAndReportUseSiteDiagnostics(BoundExpression tuple, SyntaxNode syntax, FieldSymbol field) { // Use default field rather than implicitly named fields since // fields from inferred names are not usable in C# 7.0. field = field.CorrespondingTupleField ?? field; UseSiteInfo<AssemblySymbol> useSiteInfo = field.GetUseSiteInfo(); if (useSiteInfo.DiagnosticInfo?.Severity != DiagnosticSeverity.Error) { useSiteInfo = useSiteInfo.AdjustDiagnosticInfo(null); } _diagnostics.Add(useSiteInfo, syntax.Location); return MakeTupleFieldAccess(syntax, field, tuple); } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/CSharp/Test/Semantic/Semantics/ImplicitlyTypeArraysTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ImplicitlyTypeArraysTests : SemanticModelTestBase { #region "Functionality tests" [Fact] public void ImplicitlyTypedArrayLocal() { var compilation = CreateCompilation(@" class M {} class C { public void F() { var a = new[] { new M() }; } } "); compilation.VerifyDiagnostics(); var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("F").Single(); var diagnostics = new DiagnosticBag(); var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics)); var locDecl = (BoundLocalDeclaration)block.Statements.Single(); var localA = (ArrayTypeSymbol)locDecl.DeclaredTypeOpt.Display; var typeM = compilation.GlobalNamespace.GetMember<TypeSymbol>("M"); Assert.Equal(typeM, localA.ElementType); } [Fact] public void ImplicitlyTypedArray_BindArrayInitializer() { var text = @" class C { public void F() { var a = ""; var b = new[] { ""hello"", /*<bind>*/ a /*</bind>*/, null}; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Local, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); Assert.NotNull(info.Type); Assert.NotNull(info.ConvertedType); } [Fact] public void ImplicitlyTypedArray_BindImplicitlyTypedLocal() { var text = @" class C { public void F() { /*<bind>*/ var a /*</bind>*/ = new[] { ""hello"", "", null}; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var symInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String[]", symInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.ArrayType, symInfo.Symbol.Kind); var typeInfo = model.GetTypeInfo(expr); Assert.NotNull(typeInfo.Type); Assert.NotNull(typeInfo.ConvertedType); } #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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ImplicitlyTypeArraysTests : SemanticModelTestBase { #region "Functionality tests" [Fact] public void ImplicitlyTypedArrayLocal() { var compilation = CreateCompilation(@" class M {} class C { public void F() { var a = new[] { new M() }; } } "); compilation.VerifyDiagnostics(); var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("F").Single(); var diagnostics = new DiagnosticBag(); var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics)); var locDecl = (BoundLocalDeclaration)block.Statements.Single(); var localA = (ArrayTypeSymbol)locDecl.DeclaredTypeOpt.Display; var typeM = compilation.GlobalNamespace.GetMember<TypeSymbol>("M"); Assert.Equal(typeM, localA.ElementType); } [Fact] public void ImplicitlyTypedArray_BindArrayInitializer() { var text = @" class C { public void F() { var a = ""; var b = new[] { ""hello"", /*<bind>*/ a /*</bind>*/, null}; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Local, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); Assert.NotNull(info.Type); Assert.NotNull(info.ConvertedType); } [Fact] public void ImplicitlyTypedArray_BindImplicitlyTypedLocal() { var text = @" class C { public void F() { /*<bind>*/ var a /*</bind>*/ = new[] { ""hello"", "", null}; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var symInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String[]", symInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.ArrayType, symInfo.Symbol.Kind); var typeInfo = model.GetTypeInfo(expr); Assert.NotNull(typeInfo.Type); Assert.NotNull(typeInfo.ConvertedType); } #endregion } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ICoalesceAssignmentOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.IOperation)] public class IOperationTests_ICoalesceAssignmentOperation : SemanticModelTestBase { [Fact] public void CoalesceAssignment_SimpleCase() { string source = @" class C { static void M(object o1, object o2) { /*<bind>*/o1 ??= o2/*</bind>*/; } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: System.Object) (Syntax: 'o1 ??= o2') Target: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_WithConversion() { string source = @" class C { static void M(object o1, string s1) { /*<bind>*/o1 ??= s1/*</bind>*/; } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: System.Object) (Syntax: 'o1 ??= s1') Target: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 's1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_NoConversion() { string source = @" class C { static void M(C c1, string s1) { /*<bind>*/c1 ??= s1/*</bind>*/; } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: ?, IsInvalid) (Syntax: 'c1 ??= s1') Target: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c1') Value: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 's1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,19): error CS0019: Operator '??=' cannot be applied to operands of type 'C' and 'string' // /*<bind>*/c1 ??= s1/*</bind>*/; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c1 ??= s1").WithArguments("??=", "C", "string").WithLocation(6, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_ValueTypeLeft() { string source = @" class C { static void M(int i1, string s1) { /*<bind>*/i1 ??= s1/*</bind>*/; } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: ?, IsInvalid) (Syntax: 'i1 ??= s1') Target: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i1') Value: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 's1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,19): error CS0019: Operator '??=' cannot be applied to operands of type 'int' and 'string' // /*<bind>*/i1 ??= s1/*</bind>*/; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i1 ??= s1").WithArguments("??=", "int", "string").WithLocation(6, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_MissingLeftAndRight() { string source = @" class C { static void M() { /*<bind>*/o1 ??= o2/*</bind>*/; } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: ?, IsInvalid) (Syntax: 'o1 ??= o2') Target: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'o1') Children(0) Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'o2') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,19): error CS0103: The name 'o1' does not exist in the current context // /*<bind>*/o1 ??= o2/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "o1").WithArguments("o1").WithLocation(6, 19), // file.cs(6,26): error CS0103: The name 'o2' does not exist in the current context // /*<bind>*/o1 ??= o2/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "o2").WithArguments("o2").WithLocation(6, 26) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_AsExpression() { string source = @" class C { static void M(object o1, object o2) { /*<bind>*/M2(o1 ??= o2)/*</bind>*/; } static void M2(object o) {} } "; string expectedOperationTree = @" IInvocationOperation (void C.M2(System.Object o)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(o1 ??= o2)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null) (Syntax: 'o1 ??= o2') ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: System.Object) (Syntax: 'o1 ??= o2') Target: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') InConversion: CommonConversion (Exists: True, 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 expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_CheckedDynamic() { string source = @" class C { static void M(dynamic d1, dynamic d2) { checked { /*<bind>*/d1 ??= d2/*</bind>*/; } } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: dynamic) (Syntax: 'd1 ??= d2') Target: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_NullValueAndTarget() { var comp = CreateCompilation(@" class C { static void M() { /*<bind>*/??=/*</bind>*/; } } "); string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: ?, IsInvalid) (Syntax: '/*<bind>*/? ... /*</bind>*/') Target: IInvalidOperation (OperationKind.Invalid, Type: null) (Syntax: '') Children(0) Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(5,6): error CS1525: Invalid expression term '??=' // { Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("??=").WithLocation(5, 6), // file.cs(6,33): error CS1525: Invalid expression term ';' // /*<bind>*/??=/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 33) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); var tree = comp.SyntaxTrees[0]; var m = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); VerifyFlowGraph(comp, m, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '') Value: IInvalidOperation (OperationKind.Invalid, Type: null) (Syntax: '') Children(0) Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, IsImplicit) (Syntax: '') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, IsImplicit) (Syntax: '') Leaving: {R2} Next (Regular) Block[B4] Leaving: {R2} {R1} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: '/*<bind>*/? ... /*</bind>*/') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, IsImplicit) (Syntax: '') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "); } [Fact, CompilerTrait(CompilerFeature.Dataflow)] public void CoalesceAssignmentFlow_NullableValueTypeTarget() { var comp = CreateCompilation(@" class C { static void M(int? i1, int i2) /*<bind>*/{ i1 ??= i2; }/*</bind>*/ } "); VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 ??= i2;') Expression: ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: System.Int32) (Syntax: 'i1 ??= i2') Target: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') ", expectedDiagnostics: DiagnosticDescription.None); string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Jump if False (Regular) to Block[B2] IInvocationOperation ( System.Boolean System.Int32?.HasValue.get) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B3] Leaving: {R1} Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?, IsImplicit) (Syntax: 'i1 ??= i2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'i2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph); } [Fact, CompilerTrait(CompilerFeature.Dataflow)] public void CoalesceAssignmentFlow_WhenNullConversion() { string source = @" class C { static void M(object o1, string s1) /*<bind>*/{ o1 ??= s1; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Leaving: {R2} Next (Regular) Block[B4] Leaving: {R2} {R1} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'o1 ??= s1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 's1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's1') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact, CompilerTrait(CompilerFeature.Dataflow)] public void CoalesceAssignmentFlow_WhenNullHasFlow() { string source = @" class C { static void M(object o1, string s1, string s2) /*<bind>*/{ o1 ??= s1 ?? s2; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Leaving: {R2} Entering: {R3} {R4} Next (Regular) Block[B7] Leaving: {R2} {R1} } .locals {R3} { CaptureIds: [3] .locals {R4} { CaptureIds: [2] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's1') Value: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's1') Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 's1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1') Leaving: {R4} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1') Next (Regular) Block[B6] Leaving: {R4} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's2') Value: IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's2') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'o1 ??= s1 ?? s2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 's1 ?? s2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1 ?? s2') Next (Regular) Block[B7] Leaving: {R3} {R1} } } Block[B7] - Exit Predecessors: [B2] [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact, CompilerTrait(CompilerFeature.Dataflow)] public void CoalesceAssignmentFlow_BothSidesHaveFlow() { string source = @" class C { static void M(object o1, object o2, string s1, string s2) /*<bind>*/{ (o1 ?? o2) ??= (s1 ?? s2); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { CaptureIds: [2] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'o1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'o1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Value: IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Next (Regular) Block[B5] Leaving: {R2} Entering: {R4} } .locals {R4} { CaptureIds: [3] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Leaving: {R4} Entering: {R5} {R6} Next (Regular) Block[B10] Leaving: {R4} {R1} } .locals {R5} { CaptureIds: [5] .locals {R6} { CaptureIds: [4] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's1') Value: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's1') Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 's1') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1') Leaving: {R6} Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's1') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1') Next (Regular) Block[B9] Leaving: {R6} } Block[B8] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's2') Value: IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's2') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: '(o1 ?? o2) ... (s1 ?? s2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1 ?? s2') Next (Regular) Block[B10] Leaving: {R5} {R1} } } Block[B10] - Exit Predecessors: [B5] [B9] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,10): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // (o1 ?? o2) ??= (s1 ?? s2); Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "o1 ?? o2").WithLocation(6, 10) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact, CompilerTrait(CompilerFeature.Dataflow)] public void CoalesceAssignmentFlow_NestedUse() { string source = @" class C { static void M(object o1, object o2, object o3) /*<bind>*/{ o1 ??= (o2 ??= o3); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Leaving: {R2} Entering: {R3} {R4} Next (Regular) Block[B8] Leaving: {R2} {R1} } .locals {R3} { CaptureIds: [4] .locals {R4} { CaptureIds: [2] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Entering: {R5} .locals {R5} { CaptureIds: [3] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o2') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Leaving: {R5} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2 ??= o3') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Next (Regular) Block[B7] Leaving: {R5} {R4} } Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2 ??= o3') Value: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'o2 ??= o3') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Right: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B7] Leaving: {R4} } Block[B7] - Block Predecessors: [B5] [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'o1 ??= (o2 ??= o3)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2 ??= o3') Next (Regular) Block[B8] Leaving: {R3} {R1} } } Block[B8] - Exit Predecessors: [B2] [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact] public void CoalesceAssignmentOperation_PropertyAssignment_ReferenceTypes() { var source = @" class C { object Prop { get; set; } void M(C c) /*<bind>*/{ c.Prop ??= null; }/*</bind>*/ }"; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop') Value: IPropertyReferenceOperation: System.Object C.Prop { get; set; } (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'c.Prop') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'c.Prop') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c.Prop') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'c.Prop') Leaving: {R2} Next (Regular) Block[B4] Leaving: {R2} {R1} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'c.Prop ??= null') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'c.Prop') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact] public void CoalesceAssignmentOperation_PropertyAssignment_NullableValueTypes() { var source = @" using System; class C { int? Prop { get; set; } void M(C c) /*<bind>*/{ Console.WriteLine(c.Prop ??= 1); }/*</bind>*/ }"; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] .locals {R2} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop') Value: IPropertyReferenceOperation: System.Int32? C.Prop { get; set; } (OperationKind.PropertyReference, Type: System.Int32?) (Syntax: 'c.Prop') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'c.Prop') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop') Arguments(0) Jump if False (Regular) to Block[B3] IInvocationOperation ( System.Boolean System.Int32?.HasValue.get) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'c.Prop') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop') Arguments(0) Entering: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop ??= 1') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop') Next (Regular) Block[B4] Leaving: {R2} .locals {R3} { CaptureIds: [4] Block[B3] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop ??= 1') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop ??= 1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Next (Regular) Block[B4] Leaving: {R3} {R2} } } Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... rop ??= 1);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... Prop ??= 1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.Prop ??= 1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'c.Prop ??= 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) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.IOperation)] public class IOperationTests_ICoalesceAssignmentOperation : SemanticModelTestBase { [Fact] public void CoalesceAssignment_SimpleCase() { string source = @" class C { static void M(object o1, object o2) { /*<bind>*/o1 ??= o2/*</bind>*/; } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: System.Object) (Syntax: 'o1 ??= o2') Target: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_WithConversion() { string source = @" class C { static void M(object o1, string s1) { /*<bind>*/o1 ??= s1/*</bind>*/; } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: System.Object) (Syntax: 'o1 ??= s1') Target: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 's1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_NoConversion() { string source = @" class C { static void M(C c1, string s1) { /*<bind>*/c1 ??= s1/*</bind>*/; } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: ?, IsInvalid) (Syntax: 'c1 ??= s1') Target: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c1') Value: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 's1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,19): error CS0019: Operator '??=' cannot be applied to operands of type 'C' and 'string' // /*<bind>*/c1 ??= s1/*</bind>*/; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c1 ??= s1").WithArguments("??=", "C", "string").WithLocation(6, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_ValueTypeLeft() { string source = @" class C { static void M(int i1, string s1) { /*<bind>*/i1 ??= s1/*</bind>*/; } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: ?, IsInvalid) (Syntax: 'i1 ??= s1') Target: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i1') Value: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 's1') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,19): error CS0019: Operator '??=' cannot be applied to operands of type 'int' and 'string' // /*<bind>*/i1 ??= s1/*</bind>*/; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i1 ??= s1").WithArguments("??=", "int", "string").WithLocation(6, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_MissingLeftAndRight() { string source = @" class C { static void M() { /*<bind>*/o1 ??= o2/*</bind>*/; } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: ?, IsInvalid) (Syntax: 'o1 ??= o2') Target: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'o1') Children(0) Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'o2') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,19): error CS0103: The name 'o1' does not exist in the current context // /*<bind>*/o1 ??= o2/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "o1").WithArguments("o1").WithLocation(6, 19), // file.cs(6,26): error CS0103: The name 'o2' does not exist in the current context // /*<bind>*/o1 ??= o2/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "o2").WithArguments("o2").WithLocation(6, 26) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_AsExpression() { string source = @" class C { static void M(object o1, object o2) { /*<bind>*/M2(o1 ??= o2)/*</bind>*/; } static void M2(object o) {} } "; string expectedOperationTree = @" IInvocationOperation (void C.M2(System.Object o)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(o1 ??= o2)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o) (OperationKind.Argument, Type: null) (Syntax: 'o1 ??= o2') ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: System.Object) (Syntax: 'o1 ??= o2') Target: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') InConversion: CommonConversion (Exists: True, 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 expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_CheckedDynamic() { string source = @" class C { static void M(dynamic d1, dynamic d2) { checked { /*<bind>*/d1 ??= d2/*</bind>*/; } } } "; string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: dynamic) (Syntax: 'd1 ??= d2') Target: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void CoalesceAssignment_NullValueAndTarget() { var comp = CreateCompilation(@" class C { static void M() { /*<bind>*/??=/*</bind>*/; } } "); string expectedOperationTree = @" ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: ?, IsInvalid) (Syntax: '/*<bind>*/? ... /*</bind>*/') Target: IInvalidOperation (OperationKind.Invalid, Type: null) (Syntax: '') Children(0) Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(5,6): error CS1525: Invalid expression term '??=' // { Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("??=").WithLocation(5, 6), // file.cs(6,33): error CS1525: Invalid expression term ';' // /*<bind>*/??=/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 33) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); var tree = comp.SyntaxTrees[0]; var m = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); VerifyFlowGraph(comp, m, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '') Value: IInvalidOperation (OperationKind.Invalid, Type: null) (Syntax: '') Children(0) Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, IsImplicit) (Syntax: '') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, IsImplicit) (Syntax: '') Leaving: {R2} Next (Regular) Block[B4] Leaving: {R2} {R1} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: '/*<bind>*/? ... /*</bind>*/') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: null, IsImplicit) (Syntax: '') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "); } [Fact, CompilerTrait(CompilerFeature.Dataflow)] public void CoalesceAssignmentFlow_NullableValueTypeTarget() { var comp = CreateCompilation(@" class C { static void M(int? i1, int i2) /*<bind>*/{ i1 ??= i2; }/*</bind>*/ } "); VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 ??= i2;') Expression: ICoalesceAssignmentOperation (OperationKind.CoalesceAssignment, Type: System.Int32) (Syntax: 'i1 ??= i2') Target: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') ", expectedDiagnostics: DiagnosticDescription.None); string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Jump if False (Regular) to Block[B2] IInvocationOperation ( System.Boolean System.Int32?.HasValue.get) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B3] Leaving: {R1} Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?, IsImplicit) (Syntax: 'i1 ??= i2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'i2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(comp, expectedFlowGraph); } [Fact, CompilerTrait(CompilerFeature.Dataflow)] public void CoalesceAssignmentFlow_WhenNullConversion() { string source = @" class C { static void M(object o1, string s1) /*<bind>*/{ o1 ??= s1; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Leaving: {R2} Next (Regular) Block[B4] Leaving: {R2} {R1} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'o1 ??= s1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 's1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's1') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact, CompilerTrait(CompilerFeature.Dataflow)] public void CoalesceAssignmentFlow_WhenNullHasFlow() { string source = @" class C { static void M(object o1, string s1, string s2) /*<bind>*/{ o1 ??= s1 ?? s2; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Leaving: {R2} Entering: {R3} {R4} Next (Regular) Block[B7] Leaving: {R2} {R1} } .locals {R3} { CaptureIds: [3] .locals {R4} { CaptureIds: [2] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's1') Value: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's1') Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 's1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1') Leaving: {R4} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1') Next (Regular) Block[B6] Leaving: {R4} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's2') Value: IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's2') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'o1 ??= s1 ?? s2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 's1 ?? s2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1 ?? s2') Next (Regular) Block[B7] Leaving: {R3} {R1} } } Block[B7] - Exit Predecessors: [B2] [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact, CompilerTrait(CompilerFeature.Dataflow)] public void CoalesceAssignmentFlow_BothSidesHaveFlow() { string source = @" class C { static void M(object o1, object o2, string s1, string s2) /*<bind>*/{ (o1 ?? o2) ??= (s1 ?? s2); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { CaptureIds: [2] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'o1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'o1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Value: IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Next (Regular) Block[B5] Leaving: {R2} Entering: {R4} } .locals {R4} { CaptureIds: [3] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Leaving: {R4} Entering: {R5} {R6} Next (Regular) Block[B10] Leaving: {R4} {R1} } .locals {R5} { CaptureIds: [5] .locals {R6} { CaptureIds: [4] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's1') Value: IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's1') Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 's1') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1') Leaving: {R6} Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's1') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1') Next (Regular) Block[B9] Leaving: {R6} } Block[B8] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 's2') Value: IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 's2') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: '(o1 ?? o2) ... (s1 ?? s2)') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'o1 ?? o2') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 's1 ?? s2') Next (Regular) Block[B10] Leaving: {R5} {R1} } } Block[B10] - Exit Predecessors: [B5] [B9] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,10): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // (o1 ?? o2) ??= (s1 ?? s2); Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "o1 ?? o2").WithLocation(6, 10) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact, CompilerTrait(CompilerFeature.Dataflow)] public void CoalesceAssignmentFlow_NestedUse() { string source = @" class C { static void M(object o1, object o2, object o3) /*<bind>*/{ o1 ??= (o2 ??= o3); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Leaving: {R2} Entering: {R3} {R4} Next (Regular) Block[B8] Leaving: {R2} {R1} } .locals {R3} { CaptureIds: [4] .locals {R4} { CaptureIds: [2] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Entering: {R5} .locals {R5} { CaptureIds: [3] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o2') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Leaving: {R5} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2 ??= o3') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Next (Regular) Block[B7] Leaving: {R5} {R4} } Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2 ??= o3') Value: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'o2 ??= o3') Left: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Right: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B7] Leaving: {R4} } Block[B7] - Block Predecessors: [B5] [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'o1 ??= (o2 ??= o3)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2 ??= o3') Next (Regular) Block[B8] Leaving: {R3} {R1} } } Block[B8] - Exit Predecessors: [B2] [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact] public void CoalesceAssignmentOperation_PropertyAssignment_ReferenceTypes() { var source = @" class C { object Prop { get; set; } void M(C c) /*<bind>*/{ c.Prop ??= null; }/*</bind>*/ }"; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop') Value: IPropertyReferenceOperation: System.Object C.Prop { get; set; } (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'c.Prop') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'c.Prop') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c.Prop') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'c.Prop') Leaving: {R2} Next (Regular) Block[B4] Leaving: {R2} {R1} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'c.Prop ??= null') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'c.Prop') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [Fact] public void CoalesceAssignmentOperation_PropertyAssignment_NullableValueTypes() { var source = @" using System; class C { int? Prop { get; set; } void M(C c) /*<bind>*/{ Console.WriteLine(c.Prop ??= 1); }/*</bind>*/ }"; var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [2] .locals {R2} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop') Value: IPropertyReferenceOperation: System.Int32? C.Prop { get; set; } (OperationKind.PropertyReference, Type: System.Int32?) (Syntax: 'c.Prop') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'c.Prop') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop') Arguments(0) Jump if False (Regular) to Block[B3] IInvocationOperation ( System.Boolean System.Int32?.HasValue.get) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'c.Prop') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop') Arguments(0) Entering: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop ??= 1') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop') Next (Regular) Block[B4] Leaving: {R2} .locals {R3} { CaptureIds: [4] Block[B3] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.Prop ??= 1') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop ??= 1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'c.Prop') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Next (Regular) Block[B4] Leaving: {R3} {R2} } } Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... rop ??= 1);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... Prop ??= 1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c.Prop ??= 1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'c.Prop ??= 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) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/Test/Core/IsExternalInit.cs
// Licensed to the .NET Foundation under one or more 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 System.Runtime.CompilerServices { public static class IsExternalInit { } }
// Licensed to the .NET Foundation under one or more 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 System.Runtime.CompilerServices { public static class IsExternalInit { } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/EditorFeatures/Test/EditAndContinue/TestSourceGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal class TestSourceGenerator : DiagnosticAnalyzer, ISourceGenerator { public Action<GeneratorExecutionContext>? ExecuteImpl; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(); public void Execute(GeneratorExecutionContext context) => (ExecuteImpl ?? throw new NotImplementedException()).Invoke(context); public void Initialize(GeneratorInitializationContext context) { } public override void Initialize(AnalysisContext context) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal class TestSourceGenerator : DiagnosticAnalyzer, ISourceGenerator { public Action<GeneratorExecutionContext>? ExecuteImpl; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(); public void Execute(GeneratorExecutionContext context) => (ExecuteImpl ?? throw new NotImplementedException()).Invoke(context); public void Initialize(GeneratorInitializationContext context) { } public override void Initialize(AnalysisContext context) { } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Dependencies/PooledObjects/PooledDelegates.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.PooledObjects { /// <summary> /// Provides pooled delegate instances to help avoid closure allocations for delegates that require a state argument /// with APIs that do not provide appropriate overloads with state arguments. /// </summary> internal static class PooledDelegates { private static class DefaultDelegatePool<T> where T : class, new() { public static readonly ObjectPool<T> Instance = new(() => new T(), 20); } private static Releaser GetPooledDelegate<TPooled, TArg, TUnboundDelegate, TBoundDelegate>(TUnboundDelegate unboundDelegate, TArg argument, out TBoundDelegate boundDelegate) where TPooled : AbstractDelegateWithBoundArgument<TPooled, TArg, TUnboundDelegate, TBoundDelegate>, new() where TUnboundDelegate : Delegate where TBoundDelegate : Delegate { var obj = DefaultDelegatePool<TPooled>.Instance.Allocate(); obj.Initialize(unboundDelegate, argument); boundDelegate = obj.BoundDelegate; return new Releaser(obj); } /// <summary> /// Gets an <see cref="Action"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback(() => this.DoSomething(x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction(arg => arg.self.DoSomething(arg.x), (self: this, x), out Action action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<TArg>(Action<TArg> unboundAction, TArg argument, out Action boundAction) => GetPooledDelegate<ActionWithBoundArgument<TArg>, TArg, Action<TArg>, Action>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback(a => this.DoSomething(a, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, arg) => arg.self.DoSomething(a, arg.x), (self: this, x), out Action&lt;int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, TArg>(Action<T1, TArg> unboundAction, TArg argument, out Action<T1> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, TArg>, TArg, Action<T1, TArg>, Action<T1>>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T1, T2}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback((a, b) => this.DoSomething(a, b, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, b, arg) => arg.self.DoSomething(a, b, arg.x), (self: this, x), out Action&lt;int, int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, T2, TArg>(Action<T1, T2, TArg> unboundAction, TArg argument, out Action<T1, T2> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, T2, TArg>, TArg, Action<T1, T2, TArg>, Action<T1, T2>>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T1, T2, T3}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback((a, b, c) => this.DoSomething(a, b, c, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, b, c, arg) => arg.self.DoSomething(a, b, c, arg.x), (self: this, x), out Action&lt;int, int, int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound action.</typeparam> /// <typeparam name="T3">The type of the third parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, T2, T3, TArg>(Action<T1, T2, T3, TArg> unboundAction, TArg argument, out Action<T1, T2, T3> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, T2, T3, TArg>, TArg, Action<T1, T2, T3, TArg>, Action<T1, T2, T3>>(unboundAction, argument, out boundAction); /// <summary> /// Gets a <see cref="Func{TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate(() => this.IsSomething(x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction(arg => arg.self.IsSomething(arg.x), (self: this, x), out Func&lt;bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<TArg, TResult>(Func<TArg, TResult> unboundFunction, TArg argument, out Func<TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<TArg, TResult>, TArg, Func<TArg, TResult>, Func<TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate(a => this.IsSomething(a, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, arg) => arg.self.IsSomething(a, arg.x), (self: this, x), out Func&lt;int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, TArg, TResult>(Func<T1, TArg, TResult> unboundFunction, TArg argument, out Func<T1, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, TArg, TResult>, TArg, Func<T1, TArg, TResult>, Func<T1, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T1, T2, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate((a, b) => this.IsSomething(a, b, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, b, arg) => arg.self.IsSomething(a, b, arg.x), (self: this, x), out Func&lt;int, int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, T2, TArg, TResult>(Func<T1, T2, TArg, TResult> unboundFunction, TArg argument, out Func<T1, T2, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, T2, TArg, TResult>, TArg, Func<T1, T2, TArg, TResult>, Func<T1, T2, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T1, T2, T3, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate((a, b, c) => this.IsSomething(a, b, c, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, b, c, arg) => arg.self.IsSomething(a, b, c, arg.x), (self: this, x), out Func&lt;int, int, int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound function.</typeparam> /// <typeparam name="T3">The type of the third parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, T2, T3, TArg, TResult>(Func<T1, T2, T3, TArg, TResult> unboundFunction, TArg argument, out Func<T1, T2, T3, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, T2, T3, TArg, TResult>, TArg, Func<T1, T2, T3, TArg, TResult>, Func<T1, T2, T3, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// A releaser for a pooled delegate. /// </summary> /// <remarks> /// <para>This type is intended for use as the resource of a <c>using</c> statement. When used in this manner, /// <see cref="Dispose"/> should not be called explicitly.</para> /// /// <para>If used without a <c>using</c> statement, calling <see cref="Dispose"/> is optional. If the call is /// omitted, the object will not be returned to the pool. The behavior of this type if <see cref="Dispose"/> is /// called multiple times is undefined.</para> /// </remarks> [NonCopyable] public struct Releaser : IDisposable { private readonly Poolable _pooledObject; internal Releaser(Poolable pooledObject) { _pooledObject = pooledObject; } public void Dispose() => _pooledObject.ClearAndFree(); } internal abstract class Poolable { public abstract void ClearAndFree(); } private abstract class AbstractDelegateWithBoundArgument<TSelf, TArg, TUnboundDelegate, TBoundDelegate> : Poolable where TSelf : AbstractDelegateWithBoundArgument<TSelf, TArg, TUnboundDelegate, TBoundDelegate>, new() where TUnboundDelegate : Delegate where TBoundDelegate : Delegate { protected AbstractDelegateWithBoundArgument() { BoundDelegate = Bind(); UnboundDelegate = null!; Argument = default!; } public TBoundDelegate BoundDelegate { get; } public TUnboundDelegate UnboundDelegate { get; private set; } public TArg Argument { get; private set; } public void Initialize(TUnboundDelegate unboundDelegate, TArg argument) { UnboundDelegate = unboundDelegate; Argument = argument; } public sealed override void ClearAndFree() { Argument = default!; UnboundDelegate = null!; DefaultDelegatePool<TSelf>.Instance.Free((TSelf)this); } protected abstract TBoundDelegate Bind(); } private sealed class ActionWithBoundArgument<TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<TArg>, TArg, Action<TArg>, Action> { protected override Action Bind() => () => UnboundDelegate(Argument); } private sealed class ActionWithBoundArgument<T1, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, TArg>, TArg, Action<T1, TArg>, Action<T1>> { protected override Action<T1> Bind() => arg1 => UnboundDelegate(arg1, Argument); } private sealed class ActionWithBoundArgument<T1, T2, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, T2, TArg>, TArg, Action<T1, T2, TArg>, Action<T1, T2>> { protected override Action<T1, T2> Bind() => (arg1, arg2) => UnboundDelegate(arg1, arg2, Argument); } private sealed class ActionWithBoundArgument<T1, T2, T3, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, T2, T3, TArg>, TArg, Action<T1, T2, T3, TArg>, Action<T1, T2, T3>> { protected override Action<T1, T2, T3> Bind() => (arg1, arg2, arg3) => UnboundDelegate(arg1, arg2, arg3, Argument); } private sealed class FuncWithBoundArgument<TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<TArg, TResult>, TArg, Func<TArg, TResult>, Func<TResult>> { protected override Func<TResult> Bind() => () => UnboundDelegate(Argument); } private sealed class FuncWithBoundArgument<T1, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, TArg, TResult>, TArg, Func<T1, TArg, TResult>, Func<T1, TResult>> { protected override Func<T1, TResult> Bind() => arg1 => UnboundDelegate(arg1, Argument); } private sealed class FuncWithBoundArgument<T1, T2, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, T2, TArg, TResult>, TArg, Func<T1, T2, TArg, TResult>, Func<T1, T2, TResult>> { protected override Func<T1, T2, TResult> Bind() => (arg1, arg2) => UnboundDelegate(arg1, arg2, Argument); } private sealed class FuncWithBoundArgument<T1, T2, T3, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, T2, T3, TArg, TResult>, TArg, Func<T1, T2, T3, TArg, TResult>, Func<T1, T2, T3, TResult>> { protected override Func<T1, T2, T3, TResult> Bind() => (arg1, arg2, arg3) => UnboundDelegate(arg1, arg2, arg3, Argument); } [AttributeUsage(AttributeTargets.Struct)] private sealed class NonCopyableAttribute : Attribute { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.PooledObjects { /// <summary> /// Provides pooled delegate instances to help avoid closure allocations for delegates that require a state argument /// with APIs that do not provide appropriate overloads with state arguments. /// </summary> internal static class PooledDelegates { private static class DefaultDelegatePool<T> where T : class, new() { public static readonly ObjectPool<T> Instance = new(() => new T(), 20); } private static Releaser GetPooledDelegate<TPooled, TArg, TUnboundDelegate, TBoundDelegate>(TUnboundDelegate unboundDelegate, TArg argument, out TBoundDelegate boundDelegate) where TPooled : AbstractDelegateWithBoundArgument<TPooled, TArg, TUnboundDelegate, TBoundDelegate>, new() where TUnboundDelegate : Delegate where TBoundDelegate : Delegate { var obj = DefaultDelegatePool<TPooled>.Instance.Allocate(); obj.Initialize(unboundDelegate, argument); boundDelegate = obj.BoundDelegate; return new Releaser(obj); } /// <summary> /// Gets an <see cref="Action"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback(() => this.DoSomething(x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction(arg => arg.self.DoSomething(arg.x), (self: this, x), out Action action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<TArg>(Action<TArg> unboundAction, TArg argument, out Action boundAction) => GetPooledDelegate<ActionWithBoundArgument<TArg>, TArg, Action<TArg>, Action>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback(a => this.DoSomething(a, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, arg) => arg.self.DoSomething(a, arg.x), (self: this, x), out Action&lt;int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, TArg>(Action<T1, TArg> unboundAction, TArg argument, out Action<T1> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, TArg>, TArg, Action<T1, TArg>, Action<T1>>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T1, T2}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback((a, b) => this.DoSomething(a, b, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, b, arg) => arg.self.DoSomething(a, b, arg.x), (self: this, x), out Action&lt;int, int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, T2, TArg>(Action<T1, T2, TArg> unboundAction, TArg argument, out Action<T1, T2> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, T2, TArg>, TArg, Action<T1, T2, TArg>, Action<T1, T2>>(unboundAction, argument, out boundAction); /// <summary> /// Gets an <see cref="Action{T1, T2, T3}"/> delegate, which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>. The resulting <paramref name="boundAction"/> may be called any number of times /// until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a callback action that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithActionCallback((a, b, c) => this.DoSomething(a, b, c, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// callback action:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledAction((a, b, c, arg) => arg.self.DoSomething(a, b, c, arg.x), (self: this, x), out Action&lt;int, int, int&gt; action); /// RunWithActionCallback(action); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound action.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound action.</typeparam> /// <typeparam name="T3">The type of the third parameter of the bound action.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundAction"/>.</typeparam> /// <param name="unboundAction">The unbound action delegate.</param> /// <param name="argument">The argument to pass to the unbound action delegate.</param> /// <param name="boundAction">A delegate which calls <paramref name="unboundAction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledAction<T1, T2, T3, TArg>(Action<T1, T2, T3, TArg> unboundAction, TArg argument, out Action<T1, T2, T3> boundAction) => GetPooledDelegate<ActionWithBoundArgument<T1, T2, T3, TArg>, TArg, Action<T1, T2, T3, TArg>, Action<T1, T2, T3>>(unboundAction, argument, out boundAction); /// <summary> /// Gets a <see cref="Func{TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate(() => this.IsSomething(x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction(arg => arg.self.IsSomething(arg.x), (self: this, x), out Func&lt;bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<TArg, TResult>(Func<TArg, TResult> unboundFunction, TArg argument, out Func<TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<TArg, TResult>, TArg, Func<TArg, TResult>, Func<TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate(a => this.IsSomething(a, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, arg) => arg.self.IsSomething(a, arg.x), (self: this, x), out Func&lt;int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, TArg, TResult>(Func<T1, TArg, TResult> unboundFunction, TArg argument, out Func<T1, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, TArg, TResult>, TArg, Func<T1, TArg, TResult>, Func<T1, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T1, T2, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate((a, b) => this.IsSomething(a, b, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, b, arg) => arg.self.IsSomething(a, b, arg.x), (self: this, x), out Func&lt;int, int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, T2, TArg, TResult>(Func<T1, T2, TArg, TResult> unboundFunction, TArg argument, out Func<T1, T2, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, T2, TArg, TResult>, TArg, Func<T1, T2, TArg, TResult>, Func<T1, T2, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// Gets a <see cref="Func{T1, T2, T3, TResult}"/> delegate, which calls <paramref name="unboundFunction"/> with the /// specified <paramref name="argument"/>. The resulting <paramref name="boundFunction"/> may be called any /// number of times until the returned <see cref="Releaser"/> is disposed. /// </summary> /// <example> /// <para>The following example shows the use of a capturing delegate for a predicate that requires an /// argument:</para> /// /// <code> /// int x = 3; /// RunWithPredicate((a, b, c) => this.IsSomething(a, b, c, x)); /// </code> /// /// <para>The following example shows the use of a pooled delegate to avoid capturing allocations for the same /// predicate:</para> /// /// <code> /// int x = 3; /// using var _ = GetPooledFunction((a, b, c, arg) => arg.self.IsSomething(a, b, c, arg.x), (self: this, x), out Func&lt;int, int, int, bool&gt; predicate); /// RunWithPredicate(predicate); /// </code> /// </example> /// <typeparam name="T1">The type of the first parameter of the bound function.</typeparam> /// <typeparam name="T2">The type of the second parameter of the bound function.</typeparam> /// <typeparam name="T3">The type of the third parameter of the bound function.</typeparam> /// <typeparam name="TArg">The type of argument to pass to <paramref name="unboundFunction"/>.</typeparam> /// <typeparam name="TResult">The type of the return value of the function.</typeparam> /// <param name="unboundFunction">The unbound function delegate.</param> /// <param name="argument">The argument to pass to the unbound function delegate.</param> /// <param name="boundFunction">A delegate which calls <paramref name="unboundFunction"/> with the specified /// <paramref name="argument"/>.</param> /// <returns>A disposable <see cref="Releaser"/> which returns the object to the delegate pool.</returns> public static Releaser GetPooledFunction<T1, T2, T3, TArg, TResult>(Func<T1, T2, T3, TArg, TResult> unboundFunction, TArg argument, out Func<T1, T2, T3, TResult> boundFunction) => GetPooledDelegate<FuncWithBoundArgument<T1, T2, T3, TArg, TResult>, TArg, Func<T1, T2, T3, TArg, TResult>, Func<T1, T2, T3, TResult>>(unboundFunction, argument, out boundFunction); /// <summary> /// A releaser for a pooled delegate. /// </summary> /// <remarks> /// <para>This type is intended for use as the resource of a <c>using</c> statement. When used in this manner, /// <see cref="Dispose"/> should not be called explicitly.</para> /// /// <para>If used without a <c>using</c> statement, calling <see cref="Dispose"/> is optional. If the call is /// omitted, the object will not be returned to the pool. The behavior of this type if <see cref="Dispose"/> is /// called multiple times is undefined.</para> /// </remarks> [NonCopyable] public struct Releaser : IDisposable { private readonly Poolable _pooledObject; internal Releaser(Poolable pooledObject) { _pooledObject = pooledObject; } public void Dispose() => _pooledObject.ClearAndFree(); } internal abstract class Poolable { public abstract void ClearAndFree(); } private abstract class AbstractDelegateWithBoundArgument<TSelf, TArg, TUnboundDelegate, TBoundDelegate> : Poolable where TSelf : AbstractDelegateWithBoundArgument<TSelf, TArg, TUnboundDelegate, TBoundDelegate>, new() where TUnboundDelegate : Delegate where TBoundDelegate : Delegate { protected AbstractDelegateWithBoundArgument() { BoundDelegate = Bind(); UnboundDelegate = null!; Argument = default!; } public TBoundDelegate BoundDelegate { get; } public TUnboundDelegate UnboundDelegate { get; private set; } public TArg Argument { get; private set; } public void Initialize(TUnboundDelegate unboundDelegate, TArg argument) { UnboundDelegate = unboundDelegate; Argument = argument; } public sealed override void ClearAndFree() { Argument = default!; UnboundDelegate = null!; DefaultDelegatePool<TSelf>.Instance.Free((TSelf)this); } protected abstract TBoundDelegate Bind(); } private sealed class ActionWithBoundArgument<TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<TArg>, TArg, Action<TArg>, Action> { protected override Action Bind() => () => UnboundDelegate(Argument); } private sealed class ActionWithBoundArgument<T1, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, TArg>, TArg, Action<T1, TArg>, Action<T1>> { protected override Action<T1> Bind() => arg1 => UnboundDelegate(arg1, Argument); } private sealed class ActionWithBoundArgument<T1, T2, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, T2, TArg>, TArg, Action<T1, T2, TArg>, Action<T1, T2>> { protected override Action<T1, T2> Bind() => (arg1, arg2) => UnboundDelegate(arg1, arg2, Argument); } private sealed class ActionWithBoundArgument<T1, T2, T3, TArg> : AbstractDelegateWithBoundArgument<ActionWithBoundArgument<T1, T2, T3, TArg>, TArg, Action<T1, T2, T3, TArg>, Action<T1, T2, T3>> { protected override Action<T1, T2, T3> Bind() => (arg1, arg2, arg3) => UnboundDelegate(arg1, arg2, arg3, Argument); } private sealed class FuncWithBoundArgument<TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<TArg, TResult>, TArg, Func<TArg, TResult>, Func<TResult>> { protected override Func<TResult> Bind() => () => UnboundDelegate(Argument); } private sealed class FuncWithBoundArgument<T1, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, TArg, TResult>, TArg, Func<T1, TArg, TResult>, Func<T1, TResult>> { protected override Func<T1, TResult> Bind() => arg1 => UnboundDelegate(arg1, Argument); } private sealed class FuncWithBoundArgument<T1, T2, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, T2, TArg, TResult>, TArg, Func<T1, T2, TArg, TResult>, Func<T1, T2, TResult>> { protected override Func<T1, T2, TResult> Bind() => (arg1, arg2) => UnboundDelegate(arg1, arg2, Argument); } private sealed class FuncWithBoundArgument<T1, T2, T3, TArg, TResult> : AbstractDelegateWithBoundArgument<FuncWithBoundArgument<T1, T2, T3, TArg, TResult>, TArg, Func<T1, T2, T3, TArg, TResult>, Func<T1, T2, T3, TResult>> { protected override Func<T1, T2, T3, TResult> Bind() => (arg1, arg2, arg3) => UnboundDelegate(arg1, arg2, arg3, Argument); } [AttributeUsage(AttributeTargets.Struct)] private sealed class NonCopyableAttribute : Attribute { } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/VisualStudio/Xaml/Impl/xlf/Resources.tr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="tr" original="../Resources.resx"> <body> <trans-unit id="RemoveAndSortNamespacesWithAccelerator"> <source>Remove &amp;and Sort Namespaces</source> <target state="translated">Ad Alanlarını Kaldır &amp;ve Sırala</target> <note /> </trans-unit> <trans-unit id="RemoveUnnecessaryNamespaces"> <source>Remove Unnecessary Namespaces</source> <target state="translated">Gereksiz Ad Alanlarını Kaldır</target> <note /> </trans-unit> <trans-unit id="Sort_Namespaces"> <source>&amp;Sort Namespaces</source> <target state="translated">&amp;Ad Alanlarını Sırala</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="tr" original="../Resources.resx"> <body> <trans-unit id="RemoveAndSortNamespacesWithAccelerator"> <source>Remove &amp;and Sort Namespaces</source> <target state="translated">Ad Alanlarını Kaldır &amp;ve Sırala</target> <note /> </trans-unit> <trans-unit id="RemoveUnnecessaryNamespaces"> <source>Remove Unnecessary Namespaces</source> <target state="translated">Gereksiz Ad Alanlarını Kaldır</target> <note /> </trans-unit> <trans-unit id="Sort_Namespaces"> <source>&amp;Sort Namespaces</source> <target state="translated">&amp;Ad Alanlarını Sırala</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IVariableDeclaration.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.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase #Region "Dim Declarations" <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub VariableDeclarator() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 As Integer'BIND:"Dim i1 As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1 As Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1 As Integer'BIND:"Dim i1 As Integer" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleVariableDeclarations() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 As Integer, i2 As Integer, b1 As Boolean'BIND:"Dim i1 As Integer, i2 As Integer, b1 As Boolean" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (3 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1 As I ... As Boolean') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'b1 As Boolean') Declarators: IVariableDeclaratorOperation (Symbol: b1 As System.Boolean) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b1') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1 As Integer, i2 As Integer, b1 As Boolean'BIND:"Dim i1 As Integer, i2 As Integer, b1 As Boolean" ~~ BC42024: Unused local variable: 'i2'. Dim i1 As Integer, i2 As Integer, b1 As Boolean'BIND:"Dim i1 As Integer, i2 As Integer, b1 As Boolean" ~~ BC42024: Unused local variable: 'b1'. Dim i1 As Integer, i2 As Integer, b1 As Boolean'BIND:"Dim i1 As Integer, i2 As Integer, b1 As Boolean" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub VariableDeclaratorNoType() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim i1'BIND:"Dim i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1'BIND:"Dim i1" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleVariableDeclarationNoTypes() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim i1, i2'BIND:"Dim i1, i2" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1, i2') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1, i2'BIND:"Dim i1, i2" ~~ BC42024: Unused local variable: 'i2'. Dim i1, i2'BIND:"Dim i1, i2" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub InvalidMultipleVariableDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim i1 As Integer,'BIND:"Dim i1 As Integer," End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim i1 As Integer,') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: '') Declarators: IVariableDeclaratorOperation (Symbol: As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1 As Integer,'BIND:"Dim i1 As Integer," ~~ BC30203: Identifier expected. Dim i1 As Integer,'BIND:"Dim i1 As Integer," ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub InvalidMultipleVariableDeclarationsNoType() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim i1,'BIND:"Dim i1," End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim i1,') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1,') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1,'BIND:"Dim i1," ~~ BC30203: Identifier expected. Dim i1,'BIND:"Dim i1," ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub VariableDeclaratorLocalReferenceInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 = 1 Dim i2 = i1'BIND:"Dim i2 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i2 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleVariableDeclarationLocalReferenceInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 = 1 Dim i2 = i1, i3 = i1'BIND:"Dim i2 = i1, i3 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i2 = i1, i3 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i3 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i3 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i3') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub VariableDeclaratorExpressionInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 = ReturnInt()'BIND:"Dim i1 = ReturnInt()" End Sub Function ReturnInt() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1 = ReturnInt()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = ReturnInt()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ReturnInt()') IInvocationOperation (Function Program.ReturnInt() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'ReturnInt()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleVariableDeclarationExpressionInitializers() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 = ReturnInt(), i2 = ReturnInt()'BIND:"Dim i1 = ReturnInt(), i2 = ReturnInt()" End Sub Function ReturnInt() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1 = Re ... ReturnInt()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = ReturnInt()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ReturnInt()') IInvocationOperation (Function Program.ReturnInt() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'ReturnInt()') Instance Receiver: null Arguments(0) IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = ReturnInt()') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ReturnInt()') IInvocationOperation (Function Program.ReturnInt() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'ReturnInt()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub DimAsNew() Dim source = <![CDATA[ Module Program Class C End Class Sub Main(args As String()) Dim p1 As New C'BIND:"Dim p1 As New C" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim p1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'p1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: p1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleDimAsNew() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1, i2 As New Integer'BIND:"Dim i1, i2 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1, i2 ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub DimAsNewNoObject() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 As New'BIND:"Dim i1 As New" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim i1 As New') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 As New') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'New') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. Dim i1 As New'BIND:"Dim i1 As New" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleDimAsNewNoObject() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1, i2 As New'BIND:"Dim i1, i2 As New" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim i1, i2 As New') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1, i2 As New') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'New') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. Dim i1, i2 As New'BIND:"Dim i1, i2 As New" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MixedDimAsNewAndEqualsDeclarations() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1, i2 As New Integer, b1 As Boolean = False'BIND:"Dim i1, i2 As New Integer, b1 As Boolean = False" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1, i2 ... ean = False') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'b1 As Boolean = False') Declarators: IVariableDeclaratorOperation (Symbol: b1 As System.Boolean) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= False') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'False') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MixedDimAsNewAndEqualsDeclarationsReversedOrder() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim b1 As Boolean, i1, i2 As New Integer'BIND:"Dim b1 As Boolean, i1, i2 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim b1 As B ... New Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'b1 As Boolean') Declarators: IVariableDeclaratorOperation (Symbol: b1 As System.Boolean) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b1') Initializer: null Initializer: null IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'b1'. Dim b1 As Boolean, i1, i2 As New Integer'BIND:"Dim b1 As Boolean, i1, i2 As New Integer" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ArrayDeclarationWithLength() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1(2) As Integer'BIND:"Dim i1(2) As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1(2) As Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1(2) As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1(2)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'i1(2)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'i1(2)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ArrayDeclarationMultipleVariables() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1(), i2 As Integer'BIND:"Dim i1(), i2 As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1(), i2 As Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1(), i2 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1()') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1(), i2 As Integer'BIND:"Dim i1(), i2 As Integer" ~~ BC42024: Unused local variable: 'i2'. Dim i1(), i2 As Integer'BIND:"Dim i1(), i2 As Integer" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ArrayDeclarationInvalidAsNew() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1(2) As New Integer'BIND:"Dim i1(2) As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim i1(2) As New Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1(2) As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1(2)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'i1(2)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'i1(2)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'As New Integer') Children(1): IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32, IsInvalid) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30053: Arrays cannot be declared with 'New'. Dim i1(2) As New Integer'BIND:"Dim i1(2) As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub ArrayRangeDeclaration() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim a(0 To 4) As Integer'BIND:"a(0 To 4) As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a(0 To 4) As Integer') Declarators: IVariableDeclaratorOperation (Symbol: a As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a(0 To 4)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'a(0 To 4)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'a(0 To 4)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 5, IsImplicit) (Syntax: '0 To 4') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '0 To 4') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub ArrayDeclarationCollectionInitializer() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim s As String() = {"Hello", "World"}'BIND:"s As String() = {"Hello", "World"}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 's As String ... ", "World"}') Declarators: IVariableDeclaratorOperation (Symbol: s As System.String()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= {"Hello", "World"}') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String()) (Syntax: '{"Hello", "World"}') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '{"Hello", "World"}') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: '{"Hello", "World"}') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello") (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World") (Syntax: '"World"') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub PercentTypeSpecifierWithNullableAndInitializer() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim d%? = 42'BIND:"d%? = 42" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'd%? = 42') Declarators: IVariableDeclaratorOperation (Symbol: d As System.Nullable(Of System.Int32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd%?') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 42') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '42') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub MultipleIdentifiersWithSingleInitializer_Invalid() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim d, x%? = 42'BIND:"d, x%? = 42" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'd, x%? = 42') Declarators: IVariableDeclaratorOperation (Symbol: d As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'd') Initializer: null IVariableDeclaratorOperation (Symbol: x As System.Nullable(Of System.Int32)) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x%?') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= 42') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: '42') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Dim d, x%? = 42'BIND:"d, x%? = 42" ~ BC42024: Unused local variable: 'd'. Dim d, x%? = 42'BIND:"d, x%? = 42" ~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Dim d, x%? = 42'BIND:"d, x%? = 42" ~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiersWithSingleInitializer_Invalid_ManyIdentifiers() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() #Disable Warning BC42024 Dim a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z As Integer = 1'BIND:"a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z As Integer = 1" #Enable Warning BC42024 End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (26 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a, b, c, d, ... Integer = 1') Declarators: IVariableDeclaratorOperation (Symbol: a As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a') Initializer: null IVariableDeclaratorOperation (Symbol: b As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'b') Initializer: null IVariableDeclaratorOperation (Symbol: c As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c') Initializer: null IVariableDeclaratorOperation (Symbol: d As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'd') Initializer: null IVariableDeclaratorOperation (Symbol: e As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'e') Initializer: null IVariableDeclaratorOperation (Symbol: f As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'f') Initializer: null IVariableDeclaratorOperation (Symbol: g As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'g') Initializer: null IVariableDeclaratorOperation (Symbol: h As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'h') Initializer: null IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i') Initializer: null IVariableDeclaratorOperation (Symbol: j As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'j') Initializer: null IVariableDeclaratorOperation (Symbol: k As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'k') Initializer: null IVariableDeclaratorOperation (Symbol: l As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'l') Initializer: null IVariableDeclaratorOperation (Symbol: m As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'm') Initializer: null IVariableDeclaratorOperation (Symbol: n As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'n') Initializer: null IVariableDeclaratorOperation (Symbol: o As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'o') Initializer: null IVariableDeclaratorOperation (Symbol: p As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p') Initializer: null IVariableDeclaratorOperation (Symbol: q As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'q') Initializer: null IVariableDeclaratorOperation (Symbol: r As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'r') Initializer: null IVariableDeclaratorOperation (Symbol: s As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's') Initializer: null IVariableDeclaratorOperation (Symbol: t As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 't') Initializer: null IVariableDeclaratorOperation (Symbol: u As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'u') Initializer: null IVariableDeclaratorOperation (Symbol: v As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'v') Initializer: null IVariableDeclaratorOperation (Symbol: w As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'w') Initializer: null IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y') Initializer: null IVariableDeclaratorOperation (Symbol: z As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'z') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Dim a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z As Integer = 1'BIND:"a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z As Integer = 1" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub SingleIdentifierArray_Initializer() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim x() As Integer = New Integer() {1, 2, 3, 4}'BIND:"Dim x() As Integer = New Integer() {1, 2, 3, 4}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim x() As ... 1, 2, 3, 4}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'x() As Inte ... 1, 2, 3, 4}') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x()') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New Integ ... 1, 2, 3, 4}') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 1, 2, 3, 4}') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: 'New Integer ... 1, 2, 3, 4}') Initializer: IArrayInitializerOperation (4 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4}') Element Values(4): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub SingleIdentifier_ArrayBoundsAndInitializer() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim x(1) As Integer = New Integer() {1, 2, 3, 4}'BIND:"Dim x(1) As Integer = New Integer() {1, 2, 3, 4}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim x(1) As ... 1, 2, 3, 4}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'x(1) As Int ... 1, 2, 3, 4}') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x(1)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid, IsImplicit) (Syntax: 'x(1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'x(1)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 2, IsInvalid, IsImplicit) (Syntax: '1') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New Integ ... 1, 2, 3, 4}') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 1, 2, 3, 4}') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: 'New Integer ... 1, 2, 3, 4}') Initializer: IArrayInitializerOperation (4 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4}') Element Values(4): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Dim x(1) As Integer = New Integer() {1, 2, 3, 4}'BIND:"Dim x(1) As Integer = New Integer() {1, 2, 3, 4}" ~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiers_ArrayAndAsNew() Dim source = <![CDATA[ Option Strict On Module M1 Sub Sub1() Dim x(1), y(2) As New Integer'BIND:"Dim x(1), y(2) As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim x(1), y ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'x(1), y(2) ... New Integer') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x(1)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'x(1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'x(1)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y(2)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'y(2)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'y(2)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'As New Integer') Children(1): IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32, IsInvalid) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30053: Arrays cannot be declared with 'New'. Dim x(1), y(2) As New Integer'BIND:"Dim x(1), y(2) As New Integer" ~~~ BC30053: Arrays cannot be declared with 'New'. Dim x(1), y(2) As New Integer'BIND:"Dim x(1), y(2) As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiers_MixedArrayAndNonArray() Dim source = <![CDATA[ Option Strict On Module M1 Sub Sub1() Dim x(10), y As Integer'BIND:"Dim x(10), y As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim x(10), y As Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'x(10), y As Integer') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x(10)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'x(10)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'x(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'y'. Dim x(10), y As Integer'BIND:"Dim x(10), y As Integer" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiers_MixedArrayAndNonArrayAsNew_ArrayFirst() Dim source = <![CDATA[ Option Strict On Module M1 Sub Sub1() Dim x(10), y As New Integer'BIND:"Dim x(10), y As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim x(10), ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'x(10), y As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x(10)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'x(10)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'x(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'As New Integer') Children(1): IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32, IsInvalid) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30053: Arrays cannot be declared with 'New'. Dim x(10), y As New Integer'BIND:"Dim x(10), y As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiers_MixedArrayAndNonArrayAsNew_ArrayLast() Dim source = <![CDATA[ Option Strict On Module M1 Sub Sub1() Dim x, y(10) As New Integer'BIND:"Dim x, y(10) As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim x, y(10 ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'x, y(10) As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y(10)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'y(10)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'y(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32, IsInvalid) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30053: Arrays cannot be declared with 'New'. Dim x, y(10) As New Integer'BIND:"Dim x, y(10) As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiers_MultipleArrays() Dim source = <![CDATA[ Option Strict On Module M1 Sub Sub1() Dim x%(10), y$(11)'BIND:"Dim x%(10), y$(11)" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim x%(10), y$(11)') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'x%(10), y$(11)') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x%(10)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'x%(10)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'x%(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.String()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y$(11)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'y$(11)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String(), IsImplicit) (Syntax: 'y$(11)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 12, IsImplicit) (Syntax: '11') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11) (Syntax: '11') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '11') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub #End Region #Region "Using Statements" <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub UsingStatementDeclarationAsNew() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As New C'BIND:"Using c1 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/17917"), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub UsingStatementDeclaration() Dim source = <![CDATA[ Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As C = New C'BIND:"c1 As C = New C" Console.WriteLine(c1) End Using End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationStatement (1 declarators) (OperationKind.VariableDeclarationStatement) (Syntax: 'c1 As C = New C') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1') Variables: Local_1: c1 As Program.C Initializer: IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub #End Region #Region "Const Declarations" <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstDeclaration() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 As Integer = 1'BIND:"Const i1 As Integer = 1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Const i1 As Integer = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As Integer = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1 As Integer = 1'BIND:"Const i1 As Integer = 1" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstMultipleDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const i1 = 1, i2 = 2'BIND:"Const i1 = 1, i2 = 2" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Const i1 = 1, i2 = 2') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = 2') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1 = 1, i2 = 2'BIND:"Const i1 = 1, i2 = 2" ~~ BC42099: Unused local constant: 'i2'. Const i1 = 1, i2 = 2'BIND:"Const i1 = 1, i2 = 2" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstAsNew() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 As New Integer'BIND:"Const i1 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 As New Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i1') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30438: Constants must have a value. Const i1 As New Integer'BIND:"Const i1 As New Integer" ~~ BC30246: 'New' is not valid on a local constant declaration. Const i1 As New Integer'BIND:"Const i1 As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstAsNewMultipleDeclarations() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1, i ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i1') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30438: Constants must have a value. Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" ~~ BC42099: Unused local constant: 'i1'. Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" ~~ BC30438: Constants must have a value. Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" ~~ BC30246: 'New' is not valid on a local constant declaration. Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" ~~~ BC30246: 'New' is not valid on a local constant declaration. Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstSingleDeclarationNoType() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = 1'BIND:"Const i1 = 1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Const i1 = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1 = 1'BIND:"Const i1 = 1" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstMultipleDeclarationsNoTypes() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = 1, i2 = 'BIND:"Const i1 = 1, i2 = " End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 = 1, i2 = ') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i2 = ') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1 = 1, i2 = 'BIND:"Const i1 = 1, i2 = " ~~ BC30201: Expression expected. Const i1 = 1, i2 = 'BIND:"Const i1 = 1, i2 = " ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstSingleDeclarationLocalReferenceInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = 1 Const i2 = i1'BIND:"Const i2 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Const i2 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i2'. Const i2 = i1'BIND:"Const i2 = i1" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstMultipleDeclarationsLocalReferenceInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = 1 Const i2 = i1, i3 = i1'BIND:"Const i2 = i1, i3 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Const i2 = i1, i3 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i3 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i3 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i3') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i2'. Const i2 = i1, i3 = i1'BIND:"Const i2 = i1, i3 = i1" ~~ BC42099: Unused local constant: 'i3'. Const i2 = i1, i3 = i1'BIND:"Const i2 = i1, i3 = i1" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstSingleDeclarationExpressionInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = Int1()'BIND:"Const i1 = Int1()" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 = Int1()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Int1()') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Int1()') Children(1): IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30059: Constant expression is required. Const i1 = Int1()'BIND:"Const i1 = Int1()" ~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstMultipleDeclarationsExpressionInitializers() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = Int1(), i2 = Int1()'BIND:"Const i1 = Int1(), i2 = Int1()" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 = ... i2 = Int1()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Int1()') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Int1()') Children(1): IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i2 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Int1()') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Int1()') Children(1): IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30059: Constant expression is required. Const i1 = Int1(), i2 = Int1()'BIND:"Const i1 = Int1(), i2 = Int1()" ~~~~~~ BC30059: Constant expression is required. Const i1 = Int1(), i2 = Int1()'BIND:"Const i1 = Int1(), i2 = Int1()" ~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstDimAsNewNoInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 As New'BIND:"Const i1 As New" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 As New') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 As New') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New') IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'i1') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30246: 'New' is not valid on a local constant declaration. Const i1 As New'BIND:"Const i1 As New" ~~~ BC30182: Type expected. Const i1 As New'BIND:"Const i1 As New" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstDimAsNewMultipleDeclarationsNoInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1, i2 As New'BIND:"Const i1, i2 As New" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1, i2 As New') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1, i2 As New') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New') IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'i1') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1, i2 As New'BIND:"Const i1, i2 As New" ~~ BC30246: 'New' is not valid on a local constant declaration. Const i1, i2 As New'BIND:"Const i1, i2 As New" ~~~ BC30246: 'New' is not valid on a local constant declaration. Const i1, i2 As New'BIND:"Const i1, i2 As New" ~~~ BC30182: Type expected. Const i1, i2 As New'BIND:"Const i1, i2 As New" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstInvalidMultipleDeclaration() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = 1,'BIND:"Const i1 = 1," End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 = 1,') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: '') Declarators: IVariableDeclaratorOperation (Symbol: As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid, IsImplicit) (Syntax: '') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: '') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1 = 1,'BIND:"Const i1 = 1," ~~ BC30203: Identifier expected. Const i1 = 1,'BIND:"Const i1 = 1," ~ BC30438: Constants must have a value. Const i1 = 1,'BIND:"Const i1 = 1," ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub #End Region #Region "Static Declarations" <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static i1 As Integer'BIND:"Static i1 As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 As Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Static i1 As Integer'BIND:"Static i1 As Integer" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarations() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static i1, i2 As Integer'BIND:"Static i1, i2 As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1, i2 As Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Static i1, i2 As Integer'BIND:"Static i1, i2 As Integer" ~~ BC42024: Unused local variable: 'i2'. Static i1, i2 As Integer'BIND:"Static i1, i2 As Integer" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticAsNewDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static i1 As New Integer'BIND:"Static i1 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 As New Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarationAsNew() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static i1, i2 As New Integer'BIND:"Static i1, i2 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1, ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMixedAsNewAndEqualsDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static i1, i2 As New Integer, b1 As Boolean = False'BIND:"Static i1, i2 As New Integer, b1 As Boolean = False" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1, ... ean = False') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'b1 As Boolean = False') Declarators: IVariableDeclaratorOperation (Symbol: b1 As System.Boolean) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= False') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'False') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticSingleDeclarationNoType() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = 1'BIND:"Static i1 = 1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarationsNoTypes() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = 1, i2 = 2'BIND:"Static i1 = 1, i2 = 2" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 = 1, i2 = 2') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = 2') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticSingleDeclarationLocalReferenceInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = 1 Static i2 = i1'BIND:"Static i2 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i2 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarationsLocalReferenceInitializers() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = 1 Static i2 = i1, i3 = i1'BIND:"Static i2 = i1, i3 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i2 = i1, i3 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i3 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i3 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i3') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticSingleDeclarationExpressionInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = Int1()'BIND:"Static i1 = Int1()" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 = Int1()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Int1()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'Int1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarationsExpressionInitializers() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = Int1(), i2 = Int1()'BIND:"Static i1 = Int1(), i2 = Int1()" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 = ... i2 = Int1()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Int1()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'Int1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Int1()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'Int1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticAsNewSingleDeclarationInvalidInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 As'BIND:"Static i1 As" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Static i1 As') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 As') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Static i1 As'BIND:"Static i1 As" ~~ BC30182: Type expected. Static i1 As'BIND:"Static i1 As" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticAsNewMultipleDeclarationInvalidInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1, i2 As'BIND:"Static i1, i2 As" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Static i1, i2 As') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1, i2 As') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Static i1, i2 As'BIND:"Static i1, i2 As" ~~ BC42024: Unused local variable: 'i2'. Static i1, i2 As'BIND:"Static i1, i2 As" ~~ BC30182: Type expected. Static i1, i2 As'BIND:"Static i1, i2 As" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticSingleDeclarationInvalidInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 ='BIND:"Static i1 =" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Static i1 =') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 =') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30201: Expression expected. Static i1 ='BIND:"Static i1 =" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarationsInvalidInitializers() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 =, i2 ='BIND:"Static i1 =, i2 =" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Static i1 =, i2 =') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 =') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i2 =') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30201: Expression expected. Static i1 =, i2 ='BIND:"Static i1 =, i2 =" ~ BC30201: Expression expected. Static i1 =, i2 ='BIND:"Static i1 =, i2 =" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticInvalidMultipleDeclaration() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1,'BIND:"Static i1," End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Static i1,') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1,') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Static i1,'BIND:"Static i1," ~~ BC30203: Identifier expected. Static i1,'BIND:"Static i1," ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub #End Region #Region "Initializers" <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForEqualsValueVariableInitializer() Dim source = <![CDATA[ Class Test Sub M() Dim x = 1'BIND:"= 1" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForEqualsValueVariableInitializerWithMultipleLocals() Dim source = <![CDATA[ Class Test Sub M() Dim x, y = 1'BIND:"= 1" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'x'. Dim x, y = 1'BIND:"= 1" ~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Dim x, y = 1'BIND:"= 1" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForEqualsValueVariableDeclarationWithMultipleLocals() Dim source = <![CDATA[ Class Test Sub M() Dim x, y = 1'BIND:"Dim x, y = 1" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim x, y = 1') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'x, y = 1') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'x'. Dim x, y = 1'BIND:"Dim x, y = 1" ~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Dim x, y = 1'BIND:"Dim x, y = 1" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForAsNewVariableInitializer() Dim source = <![CDATA[ Class Test Sub M() Dim x As New Test'BIND:"As New Test" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Test') IObjectCreationOperation (Constructor: Sub Test..ctor()) (OperationKind.ObjectCreation, Type: Test) (Syntax: 'New Test') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForAsNewVariableDeclaration() Dim source = <![CDATA[ Class Test Sub M() Dim x As New Test'BIND:"Dim x As New Test" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim x As New Test') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'x As New Test') Declarators: IVariableDeclaratorOperation (Symbol: x As Test) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Test') IObjectCreationOperation (Constructor: Sub Test..ctor()) (OperationKind.ObjectCreation, Type: Test) (Syntax: 'New Test') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForAsNewVariableInitializerWithMultipleLocals() Dim source = <![CDATA[ Class Test Sub M() Dim x, y As New Test'BIND:"As New Test" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Test') IObjectCreationOperation (Constructor: Sub Test..ctor()) (OperationKind.ObjectCreation, Type: Test) (Syntax: 'New Test') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForAsNewVariableDeclarationWithMultipleLocals() Dim source = <![CDATA[ Class Test Sub M() Dim x, y As New Test'BIND:"x, y As New Test" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'x, y As New Test') Declarators: IVariableDeclaratorOperation (Symbol: x As Test) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null IVariableDeclaratorOperation (Symbol: y As Test) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Test') IObjectCreationOperation (Constructor: Sub Test..ctor()) (OperationKind.ObjectCreation, Type: Test) (Syntax: 'New Test') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub #End Region #Region "Control Flow Graph" <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_01() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim a As Integer = 1 Dim b = 2 Dim c = 3, d = 4 Dim e, f As New Integer() End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32] [b As System.Int32] [c As System.Int32] [d As System.Int32] [e As System.Int32] [f As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (6) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a As Integer = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 2') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 3') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 4') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e, f As New Integer()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e') Right: IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer()') Arguments(0) Initializer: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e, f As New Integer()') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f') Right: IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer()') Arguments(0) Initializer: null Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_02() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim a As Integer a = 1 End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_03() Dim source = <![CDATA[ Imports System Public Class C Public Sub M(a As Boolean, b As Integer, c As Integer)'BIND:"Public Sub M(a As Boolean, b As Integer, c As Integer)" Dim d As Integer = If(a, b, c) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [d As System.Int32] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd As Intege ... If(a, b, c)') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b, c)') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_04() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim d As Integer = End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30201: Expression expected. Dim d As Integer = ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [d As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd As Integer =') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_05() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim d As New End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. Dim d As New ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [d As ?] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'd As New') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: ?, IsImplicit) (Syntax: 'd') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'New') Children(0) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_06() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" #Disable Warning BC42099 ' Unused local constant Const a As Integer = 1 Static b As Integer = 1 End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32] [b As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a As Integer = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IStaticLocalInitializationSemaphoreOperation (Local Symbol: b As System.Int32) (OperationKind.StaticLocalInitializationSemaphore, Type: System.Boolean, IsImplicit) (Syntax: 'b') Leaving: {R1} Next (Regular) Block[B2] Entering: {R2} .static initializer {R2} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b As Integer = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_06_WithControlFlow() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" #Disable Warning BC42099 ' Unused local constant Const a As Integer = If(True, 1, 2) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block [UnReachable] Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a As Intege ... True, 1, 2)') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(True, 1, 2)') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_07() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim a(10) As Integer End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32()] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32(), IsImplicit) (Syntax: 'a(10)') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32(), IsImplicit) (Syntax: 'a(10)') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'a(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_08() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim a(10) As Integer = 1 End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Dim a(10) As Integer = 1 ~~~~~ BC30311: Value of type 'Integer' cannot be converted to 'Integer()'. Dim a(10) As Integer = 1 ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32()] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10) As Integer = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10)') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10) As Integer = 1') Children(2): IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsInvalid, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '10') Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_09() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim a(10) As New Integer() End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30053: Arrays cannot be declared with 'New'. Dim a(10) As New Integer() ~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32()] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10) As New Integer()') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32(), IsImplicit) (Syntax: 'a(10)') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10) As New Integer()') Children(2): IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'a(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'As New Integer()') Children(1): IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32, IsInvalid) (Syntax: 'New Integer()') Arguments(0) Initializer: null Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_10() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" #Disable Warning BC42024 ' Unused local variable Dim = 1 Dim As New Integer() End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30203: Identifier expected. Dim = 1 ~ BC30183: Keyword is not valid as an identifier. Dim As New Integer() ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [ As System.Int32] [[As] As System.Object] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= 1') Left: ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_11() Dim source = <![CDATA[ Imports System Public Class C Public Sub M(a As Boolean, b As Integer, c As Integer)'BIND:"Public Sub M(a As Boolean, b As Integer, c As Integer)" Dim d As Integer = b, e As Integer = If(a, b, c) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [d As System.Int32] [e As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd As Integer = b') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd') Right: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e As Intege ... If(a, b, c)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b, c)') Next (Regular) Block[B6] Leaving: {R2} {R1} } } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_12() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" #Disable Warning BC42024 ' Unused local variable a = 1 Dim a End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC32000: Local variable 'a' cannot be referred to before it is declared. a = 1 ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Object] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a = 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: ?, IsInvalid) (Syntax: 'a') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_13() Dim source = <![CDATA[ Imports System Class C Public Property A As Object Public Property B As Object Public Sub M(b As Boolean)'BIND:"Public Sub M(b As Boolean)" Static m As Integer = If(b, 1, 2) Console.WriteLine(m) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [m As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B6] IStaticLocalInitializationSemaphoreOperation (Local Symbol: m As System.Int32) (OperationKind.StaticLocalInitializationSemaphore, Type: System.Boolean, IsImplicit) (Syntax: 'm') Next (Regular) Block[B2] Entering: {R2} .static initializer {R2} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'm As Intege ... If(b, 1, 2)') Left: ILocalReferenceOperation: m (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'm') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 1, 2)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B1] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(m)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(m)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'm') ILocalReferenceOperation: m (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'm') InConversion: CommonConversion (Exists: True, 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[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_14() Dim source = <![CDATA[ Imports System Class C Public Property A As Object Public Property B As Object Public Sub M(b As Boolean)'BIND:"Public Sub M(b As Boolean)" Static m As Integer Console.WriteLine(m) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [m As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(m)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(m)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'm') ILocalReferenceOperation: m (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'm') InConversion: CommonConversion (Exists: True, 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] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_15() Dim source = <![CDATA[ Imports System Class C Public Property A As Object Public Property B As Object Public Sub M(b As Boolean)'BIND:"Public Sub M(b As Boolean)" Console.WriteLine(b) Static m As Integer = 1 Console.WriteLine(m) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [m As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(b)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Boolean)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Jump if False (Regular) to Block[B3] IStaticLocalInitializationSemaphoreOperation (Local Symbol: m As System.Int32) (OperationKind.StaticLocalInitializationSemaphore, Type: System.Boolean, IsImplicit) (Syntax: 'm') Next (Regular) Block[B2] Entering: {R2} .static initializer {R2} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'm As Integer = 1') Left: ILocalReferenceOperation: m (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'm') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(m)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(m)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'm') ILocalReferenceOperation: m (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'm') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_16() Dim source = <![CDATA[ Imports System Class C Public Sub M(b As Boolean)'BIND:"Public Sub M(b As Boolean)" Static m1 As Integer = 1 Static m2 As Integer = 1 Console.WriteLine(m1) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [m1 As System.Int32] [m2 As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IStaticLocalInitializationSemaphoreOperation (Local Symbol: m1 As System.Int32) (OperationKind.StaticLocalInitializationSemaphore, Type: System.Boolean, IsImplicit) (Syntax: 'm1') Next (Regular) Block[B2] Entering: {R2} .static initializer {R2} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'm1 As Integer = 1') Left: ILocalReferenceOperation: m1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'm1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] [B2] Statements (0) Jump if False (Regular) to Block[B5] IStaticLocalInitializationSemaphoreOperation (Local Symbol: m2 As System.Int32) (OperationKind.StaticLocalInitializationSemaphore, Type: System.Boolean, IsImplicit) (Syntax: 'm2') Next (Regular) Block[B4] Entering: {R3} .static initializer {R3} { Block[B4] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'm2 As Integer = 1') Left: ILocalReferenceOperation: m2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'm2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(m1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(m1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'm1') ILocalReferenceOperation: m1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'm1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase #Region "Dim Declarations" <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub VariableDeclarator() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 As Integer'BIND:"Dim i1 As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1 As Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1 As Integer'BIND:"Dim i1 As Integer" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleVariableDeclarations() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 As Integer, i2 As Integer, b1 As Boolean'BIND:"Dim i1 As Integer, i2 As Integer, b1 As Boolean" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (3 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1 As I ... As Boolean') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'b1 As Boolean') Declarators: IVariableDeclaratorOperation (Symbol: b1 As System.Boolean) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b1') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1 As Integer, i2 As Integer, b1 As Boolean'BIND:"Dim i1 As Integer, i2 As Integer, b1 As Boolean" ~~ BC42024: Unused local variable: 'i2'. Dim i1 As Integer, i2 As Integer, b1 As Boolean'BIND:"Dim i1 As Integer, i2 As Integer, b1 As Boolean" ~~ BC42024: Unused local variable: 'b1'. Dim i1 As Integer, i2 As Integer, b1 As Boolean'BIND:"Dim i1 As Integer, i2 As Integer, b1 As Boolean" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub VariableDeclaratorNoType() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim i1'BIND:"Dim i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1'BIND:"Dim i1" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleVariableDeclarationNoTypes() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim i1, i2'BIND:"Dim i1, i2" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1, i2') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1, i2'BIND:"Dim i1, i2" ~~ BC42024: Unused local variable: 'i2'. Dim i1, i2'BIND:"Dim i1, i2" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub InvalidMultipleVariableDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim i1 As Integer,'BIND:"Dim i1 As Integer," End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim i1 As Integer,') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: '') Declarators: IVariableDeclaratorOperation (Symbol: As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1 As Integer,'BIND:"Dim i1 As Integer," ~~ BC30203: Identifier expected. Dim i1 As Integer,'BIND:"Dim i1 As Integer," ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub InvalidMultipleVariableDeclarationsNoType() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim i1,'BIND:"Dim i1," End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim i1,') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1,') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1,'BIND:"Dim i1," ~~ BC30203: Identifier expected. Dim i1,'BIND:"Dim i1," ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub VariableDeclaratorLocalReferenceInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 = 1 Dim i2 = i1'BIND:"Dim i2 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i2 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleVariableDeclarationLocalReferenceInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 = 1 Dim i2 = i1, i3 = i1'BIND:"Dim i2 = i1, i3 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i2 = i1, i3 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i3 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i3 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i3') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub VariableDeclaratorExpressionInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 = ReturnInt()'BIND:"Dim i1 = ReturnInt()" End Sub Function ReturnInt() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1 = ReturnInt()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = ReturnInt()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ReturnInt()') IInvocationOperation (Function Program.ReturnInt() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'ReturnInt()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleVariableDeclarationExpressionInitializers() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 = ReturnInt(), i2 = ReturnInt()'BIND:"Dim i1 = ReturnInt(), i2 = ReturnInt()" End Sub Function ReturnInt() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1 = Re ... ReturnInt()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = ReturnInt()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ReturnInt()') IInvocationOperation (Function Program.ReturnInt() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'ReturnInt()') Instance Receiver: null Arguments(0) IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = ReturnInt()') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ReturnInt()') IInvocationOperation (Function Program.ReturnInt() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'ReturnInt()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub DimAsNew() Dim source = <![CDATA[ Module Program Class C End Class Sub Main(args As String()) Dim p1 As New C'BIND:"Dim p1 As New C" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim p1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'p1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: p1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'p1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleDimAsNew() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1, i2 As New Integer'BIND:"Dim i1, i2 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1, i2 ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub DimAsNewNoObject() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1 As New'BIND:"Dim i1 As New" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim i1 As New') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 As New') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'New') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. Dim i1 As New'BIND:"Dim i1 As New" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MultipleDimAsNewNoObject() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1, i2 As New'BIND:"Dim i1, i2 As New" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim i1, i2 As New') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1, i2 As New') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'New') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. Dim i1, i2 As New'BIND:"Dim i1, i2 As New" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MixedDimAsNewAndEqualsDeclarations() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1, i2 As New Integer, b1 As Boolean = False'BIND:"Dim i1, i2 As New Integer, b1 As Boolean = False" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1, i2 ... ean = False') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'b1 As Boolean = False') Declarators: IVariableDeclaratorOperation (Symbol: b1 As System.Boolean) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= False') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'False') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub MixedDimAsNewAndEqualsDeclarationsReversedOrder() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim b1 As Boolean, i1, i2 As New Integer'BIND:"Dim b1 As Boolean, i1, i2 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim b1 As B ... New Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'b1 As Boolean') Declarators: IVariableDeclaratorOperation (Symbol: b1 As System.Boolean) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b1') Initializer: null Initializer: null IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'b1'. Dim b1 As Boolean, i1, i2 As New Integer'BIND:"Dim b1 As Boolean, i1, i2 As New Integer" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ArrayDeclarationWithLength() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1(2) As Integer'BIND:"Dim i1(2) As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1(2) As Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1(2) As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1(2)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'i1(2)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'i1(2)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ArrayDeclarationMultipleVariables() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1(), i2 As Integer'BIND:"Dim i1(), i2 As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim i1(), i2 As Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1(), i2 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1()') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Dim i1(), i2 As Integer'BIND:"Dim i1(), i2 As Integer" ~~ BC42024: Unused local variable: 'i2'. Dim i1(), i2 As Integer'BIND:"Dim i1(), i2 As Integer" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ArrayDeclarationInvalidAsNew() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Dim i1(2) As New Integer'BIND:"Dim i1(2) As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim i1(2) As New Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1(2) As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1(2)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'i1(2)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'i1(2)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'As New Integer') Children(1): IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32, IsInvalid) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30053: Arrays cannot be declared with 'New'. Dim i1(2) As New Integer'BIND:"Dim i1(2) As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub ArrayRangeDeclaration() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim a(0 To 4) As Integer'BIND:"a(0 To 4) As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a(0 To 4) As Integer') Declarators: IVariableDeclaratorOperation (Symbol: a As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a(0 To 4)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'a(0 To 4)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'a(0 To 4)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 5, IsImplicit) (Syntax: '0 To 4') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '0 To 4') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub ArrayDeclarationCollectionInitializer() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim s As String() = {"Hello", "World"}'BIND:"s As String() = {"Hello", "World"}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 's As String ... ", "World"}') Declarators: IVariableDeclaratorOperation (Symbol: s As System.String()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= {"Hello", "World"}') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String()) (Syntax: '{"Hello", "World"}') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '{"Hello", "World"}') Initializer: IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: '{"Hello", "World"}') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello") (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World") (Syntax: '"World"') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub PercentTypeSpecifierWithNullableAndInitializer() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim d%? = 42'BIND:"d%? = 42" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'd%? = 42') Declarators: IVariableDeclaratorOperation (Symbol: d As System.Nullable(Of System.Int32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd%?') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 42') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '42') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub MultipleIdentifiersWithSingleInitializer_Invalid() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim d, x%? = 42'BIND:"d, x%? = 42" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'd, x%? = 42') Declarators: IVariableDeclaratorOperation (Symbol: d As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'd') Initializer: null IVariableDeclaratorOperation (Symbol: x As System.Nullable(Of System.Int32)) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x%?') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= 42') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: '42') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Dim d, x%? = 42'BIND:"d, x%? = 42" ~ BC42024: Unused local variable: 'd'. Dim d, x%? = 42'BIND:"d, x%? = 42" ~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Dim d, x%? = 42'BIND:"d, x%? = 42" ~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiersWithSingleInitializer_Invalid_ManyIdentifiers() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() #Disable Warning BC42024 Dim a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z As Integer = 1'BIND:"a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z As Integer = 1" #Enable Warning BC42024 End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (26 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a, b, c, d, ... Integer = 1') Declarators: IVariableDeclaratorOperation (Symbol: a As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'a') Initializer: null IVariableDeclaratorOperation (Symbol: b As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'b') Initializer: null IVariableDeclaratorOperation (Symbol: c As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c') Initializer: null IVariableDeclaratorOperation (Symbol: d As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'd') Initializer: null IVariableDeclaratorOperation (Symbol: e As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'e') Initializer: null IVariableDeclaratorOperation (Symbol: f As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'f') Initializer: null IVariableDeclaratorOperation (Symbol: g As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'g') Initializer: null IVariableDeclaratorOperation (Symbol: h As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'h') Initializer: null IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i') Initializer: null IVariableDeclaratorOperation (Symbol: j As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'j') Initializer: null IVariableDeclaratorOperation (Symbol: k As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'k') Initializer: null IVariableDeclaratorOperation (Symbol: l As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'l') Initializer: null IVariableDeclaratorOperation (Symbol: m As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'm') Initializer: null IVariableDeclaratorOperation (Symbol: n As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'n') Initializer: null IVariableDeclaratorOperation (Symbol: o As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'o') Initializer: null IVariableDeclaratorOperation (Symbol: p As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'p') Initializer: null IVariableDeclaratorOperation (Symbol: q As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'q') Initializer: null IVariableDeclaratorOperation (Symbol: r As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'r') Initializer: null IVariableDeclaratorOperation (Symbol: s As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 's') Initializer: null IVariableDeclaratorOperation (Symbol: t As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 't') Initializer: null IVariableDeclaratorOperation (Symbol: u As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'u') Initializer: null IVariableDeclaratorOperation (Symbol: v As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'v') Initializer: null IVariableDeclaratorOperation (Symbol: w As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'w') Initializer: null IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y') Initializer: null IVariableDeclaratorOperation (Symbol: z As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'z') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Dim a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z As Integer = 1'BIND:"a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z As Integer = 1" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub SingleIdentifierArray_Initializer() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim x() As Integer = New Integer() {1, 2, 3, 4}'BIND:"Dim x() As Integer = New Integer() {1, 2, 3, 4}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim x() As ... 1, 2, 3, 4}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'x() As Inte ... 1, 2, 3, 4}') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x()') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New Integ ... 1, 2, 3, 4}') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 1, 2, 3, 4}') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: 'New Integer ... 1, 2, 3, 4}') Initializer: IArrayInitializerOperation (4 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4}') Element Values(4): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub SingleIdentifier_ArrayBoundsAndInitializer() Dim source = <![CDATA[ Option Strict On Imports System.Text Module M1 Sub Sub1() Dim x(1) As Integer = New Integer() {1, 2, 3, 4}'BIND:"Dim x(1) As Integer = New Integer() {1, 2, 3, 4}" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim x(1) As ... 1, 2, 3, 4}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'x(1) As Int ... 1, 2, 3, 4}') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x(1)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid, IsImplicit) (Syntax: 'x(1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'x(1)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 2, IsInvalid, IsImplicit) (Syntax: '1') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New Integ ... 1, 2, 3, 4}') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32()) (Syntax: 'New Integer ... 1, 2, 3, 4}') Dimension Sizes(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: 'New Integer ... 1, 2, 3, 4}') Initializer: IArrayInitializerOperation (4 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{1, 2, 3, 4}') Element Values(4): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Dim x(1) As Integer = New Integer() {1, 2, 3, 4}'BIND:"Dim x(1) As Integer = New Integer() {1, 2, 3, 4}" ~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiers_ArrayAndAsNew() Dim source = <![CDATA[ Option Strict On Module M1 Sub Sub1() Dim x(1), y(2) As New Integer'BIND:"Dim x(1), y(2) As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim x(1), y ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'x(1), y(2) ... New Integer') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x(1)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'x(1)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'x(1)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '1') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y(2)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'y(2)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'y(2)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: '2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'As New Integer') Children(1): IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32, IsInvalid) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30053: Arrays cannot be declared with 'New'. Dim x(1), y(2) As New Integer'BIND:"Dim x(1), y(2) As New Integer" ~~~ BC30053: Arrays cannot be declared with 'New'. Dim x(1), y(2) As New Integer'BIND:"Dim x(1), y(2) As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiers_MixedArrayAndNonArray() Dim source = <![CDATA[ Option Strict On Module M1 Sub Sub1() Dim x(10), y As Integer'BIND:"Dim x(10), y As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim x(10), y As Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'x(10), y As Integer') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x(10)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'x(10)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'x(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'y'. Dim x(10), y As Integer'BIND:"Dim x(10), y As Integer" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiers_MixedArrayAndNonArrayAsNew_ArrayFirst() Dim source = <![CDATA[ Option Strict On Module M1 Sub Sub1() Dim x(10), y As New Integer'BIND:"Dim x(10), y As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim x(10), ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'x(10), y As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x(10)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'x(10)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'x(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'As New Integer') Children(1): IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32, IsInvalid) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30053: Arrays cannot be declared with 'New'. Dim x(10), y As New Integer'BIND:"Dim x(10), y As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiers_MixedArrayAndNonArrayAsNew_ArrayLast() Dim source = <![CDATA[ Option Strict On Module M1 Sub Sub1() Dim x, y(10) As New Integer'BIND:"Dim x, y(10) As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim x, y(10 ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'x, y(10) As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y(10)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'y(10)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'y(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32, IsInvalid) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30053: Arrays cannot be declared with 'New'. Dim x, y(10) As New Integer'BIND:"Dim x, y(10) As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub MultipleIdentifiers_MultipleArrays() Dim source = <![CDATA[ Option Strict On Module M1 Sub Sub1() Dim x%(10), y$(11)'BIND:"Dim x%(10), y$(11)" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim x%(10), y$(11)') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'x%(10), y$(11)') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x%(10)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'x%(10)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'x%(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.String()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y$(11)') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'y$(11)') IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.String(), IsImplicit) (Syntax: 'y$(11)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 12, IsImplicit) (Syntax: '11') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11) (Syntax: '11') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '11') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub #End Region #Region "Using Statements" <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub UsingStatementDeclarationAsNew() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As New C'BIND:"Using c1 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/17917"), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub UsingStatementDeclaration() Dim source = <![CDATA[ Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As C = New C'BIND:"c1 As C = New C" Console.WriteLine(c1) End Using End Sub End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationStatement (1 declarators) (OperationKind.VariableDeclarationStatement) (Syntax: 'c1 As C = New C') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'c1') Variables: Local_1: c1 As Program.C Initializer: IObjectCreationExpression (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreationExpression, Type: Program.C) (Syntax: 'New C') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub #End Region #Region "Const Declarations" <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstDeclaration() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 As Integer = 1'BIND:"Const i1 As Integer = 1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Const i1 As Integer = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As Integer = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1 As Integer = 1'BIND:"Const i1 As Integer = 1" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstMultipleDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Const i1 = 1, i2 = 2'BIND:"Const i1 = 1, i2 = 2" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Const i1 = 1, i2 = 2') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = 2') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1 = 1, i2 = 2'BIND:"Const i1 = 1, i2 = 2" ~~ BC42099: Unused local constant: 'i2'. Const i1 = 1, i2 = 2'BIND:"Const i1 = 1, i2 = 2" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstAsNew() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 As New Integer'BIND:"Const i1 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 As New Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i1') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30438: Constants must have a value. Const i1 As New Integer'BIND:"Const i1 As New Integer" ~~ BC30246: 'New' is not valid on a local constant declaration. Const i1 As New Integer'BIND:"Const i1 As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstAsNewMultipleDeclarations() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1, i ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New Integer') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i1') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30438: Constants must have a value. Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" ~~ BC42099: Unused local constant: 'i1'. Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" ~~ BC30438: Constants must have a value. Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" ~~ BC30246: 'New' is not valid on a local constant declaration. Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" ~~~ BC30246: 'New' is not valid on a local constant declaration. Const i1, i2 As New Integer'BIND:"Const i1, i2 As New Integer" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstSingleDeclarationNoType() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = 1'BIND:"Const i1 = 1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Const i1 = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1 = 1'BIND:"Const i1 = 1" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstMultipleDeclarationsNoTypes() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = 1, i2 = 'BIND:"Const i1 = 1, i2 = " End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 = 1, i2 = ') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i2 = ') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= ') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1 = 1, i2 = 'BIND:"Const i1 = 1, i2 = " ~~ BC30201: Expression expected. Const i1 = 1, i2 = 'BIND:"Const i1 = 1, i2 = " ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstSingleDeclarationLocalReferenceInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = 1 Const i2 = i1'BIND:"Const i2 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Const i2 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i2'. Const i2 = i1'BIND:"Const i2 = i1" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstMultipleDeclarationsLocalReferenceInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = 1 Const i2 = i1, i3 = i1'BIND:"Const i2 = i1, i3 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Const i2 = i1, i3 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i3 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i3 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i3') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Int32, Constant: 1) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i2'. Const i2 = i1, i3 = i1'BIND:"Const i2 = i1, i3 = i1" ~~ BC42099: Unused local constant: 'i3'. Const i2 = i1, i3 = i1'BIND:"Const i2 = i1, i3 = i1" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstSingleDeclarationExpressionInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = Int1()'BIND:"Const i1 = Int1()" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 = Int1()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Int1()') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Int1()') Children(1): IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30059: Constant expression is required. Const i1 = Int1()'BIND:"Const i1 = Int1()" ~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstMultipleDeclarationsExpressionInitializers() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = Int1(), i2 = Int1()'BIND:"Const i1 = Int1(), i2 = Int1()" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 = ... i2 = Int1()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Int1()') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Int1()') Children(1): IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i2 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Int1()') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Int1()') Children(1): IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30059: Constant expression is required. Const i1 = Int1(), i2 = Int1()'BIND:"Const i1 = Int1(), i2 = Int1()" ~~~~~~ BC30059: Constant expression is required. Const i1 = Int1(), i2 = Int1()'BIND:"Const i1 = Int1(), i2 = Int1()" ~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstDimAsNewNoInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 As New'BIND:"Const i1 As New" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 As New') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 As New') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New') IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'i1') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30246: 'New' is not valid on a local constant declaration. Const i1 As New'BIND:"Const i1 As New" ~~~ BC30182: Type expected. Const i1 As New'BIND:"Const i1 As New" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstDimAsNewMultipleDeclarationsNoInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1, i2 As New'BIND:"Const i1, i2 As New" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1, i2 As New') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1, i2 As New') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New') IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'i1') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1, i2 As New'BIND:"Const i1, i2 As New" ~~ BC30246: 'New' is not valid on a local constant declaration. Const i1, i2 As New'BIND:"Const i1, i2 As New" ~~~ BC30246: 'New' is not valid on a local constant declaration. Const i1, i2 As New'BIND:"Const i1, i2 As New" ~~~ BC30182: Type expected. Const i1, i2 As New'BIND:"Const i1, i2 As New" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub ConstInvalidMultipleDeclaration() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Const i1 = 1,'BIND:"Const i1 = 1," End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Const i1 = 1,') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: '') Declarators: IVariableDeclaratorOperation (Symbol: As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid, IsImplicit) (Syntax: '') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: '') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42099: Unused local constant: 'i1'. Const i1 = 1,'BIND:"Const i1 = 1," ~~ BC30203: Identifier expected. Const i1 = 1,'BIND:"Const i1 = 1," ~ BC30438: Constants must have a value. Const i1 = 1,'BIND:"Const i1 = 1," ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub #End Region #Region "Static Declarations" <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static i1 As Integer'BIND:"Static i1 As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 As Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Static i1 As Integer'BIND:"Static i1 As Integer" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarations() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static i1, i2 As Integer'BIND:"Static i1, i2 As Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1, i2 As Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Static i1, i2 As Integer'BIND:"Static i1, i2 As Integer" ~~ BC42024: Unused local variable: 'i2'. Static i1, i2 As Integer'BIND:"Static i1, i2 As Integer" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticAsNewDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static i1 As New Integer'BIND:"Static i1 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 As New Integer') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarationAsNew() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static i1, i2 As New Integer'BIND:"Static i1, i2 As New Integer" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1, ... New Integer') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMixedAsNewAndEqualsDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Static i1, i2 As New Integer, b1 As Boolean = False'BIND:"Static i1, i2 As New Integer, b1 As Boolean = False" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1, ... ean = False') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1, i2 As New Integer') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Integer') IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'b1 As Boolean = False') Declarators: IVariableDeclaratorOperation (Symbol: b1 As System.Boolean) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= False') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'False') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticSingleDeclarationNoType() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = 1'BIND:"Static i1 = 1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarationsNoTypes() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = 1, i2 = 2'BIND:"Static i1 = 1, i2 = 2" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 = 1, i2 = 2') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = 1') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = 2') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 2') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticSingleDeclarationLocalReferenceInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = 1 Static i2 = i1'BIND:"Static i2 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i2 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarationsLocalReferenceInitializers() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = 1 Static i2 = i1, i3 = i1'BIND:"Static i2 = i1, i3 = i1" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i2 = i1, i3 = i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'i1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i3 = i1') Declarators: IVariableDeclaratorOperation (Symbol: i3 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i3') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i1') ILocalReferenceOperation: i1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'i1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticSingleDeclarationExpressionInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = Int1()'BIND:"Static i1 = Int1()" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 = Int1()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Int1()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'Int1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarationsExpressionInitializers() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 = Int1(), i2 = Int1()'BIND:"Static i1 = Int1(), i2 = Int1()" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Static i1 = ... i2 = Int1()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i1 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Int1()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'Int1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'i2 = Int1()') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Int1()') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'Int1()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation (Function Program.Int1() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Int1()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticAsNewSingleDeclarationInvalidInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 As'BIND:"Static i1 As" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Static i1 As') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 As') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Static i1 As'BIND:"Static i1 As" ~~ BC30182: Type expected. Static i1 As'BIND:"Static i1 As" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticAsNewMultipleDeclarationInvalidInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1, i2 As'BIND:"Static i1, i2 As" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Static i1, i2 As') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1, i2 As') Declarators: IVariableDeclaratorOperation (Symbol: i1 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: i2 As ?) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Static i1, i2 As'BIND:"Static i1, i2 As" ~~ BC42024: Unused local variable: 'i2'. Static i1, i2 As'BIND:"Static i1, i2 As" ~~ BC30182: Type expected. Static i1, i2 As'BIND:"Static i1, i2 As" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticSingleDeclarationInvalidInitializer() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 ='BIND:"Static i1 =" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Static i1 =') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 =') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30201: Expression expected. Static i1 ='BIND:"Static i1 =" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticMultipleDeclarationsInvalidInitializers() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1 =, i2 ='BIND:"Static i1 =, i2 =" End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Static i1 =, i2 =') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1 =') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i2 =') Declarators: IVariableDeclaratorOperation (Symbol: i2 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '=') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30201: Expression expected. Static i1 =, i2 ='BIND:"Static i1 =, i2 =" ~ BC30201: Expression expected. Static i1 =, i2 ='BIND:"Static i1 =, i2 =" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17599, "https://github.com/dotnet/roslyn/issues/17599")> Public Sub StaticInvalidMultipleDeclaration() Dim source = <![CDATA[ Module Program Sub Main(args As String()) Static i1,'BIND:"Static i1," End Sub Function Int1() As Integer Return 1 End Function End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Static i1,') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'i1,') Declarators: IVariableDeclaratorOperation (Symbol: i1 As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i1') Initializer: null IVariableDeclaratorOperation (Symbol: As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '') Initializer: null Initializer: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'i1'. Static i1,'BIND:"Static i1," ~~ BC30203: Identifier expected. Static i1,'BIND:"Static i1," ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub #End Region #Region "Initializers" <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForEqualsValueVariableInitializer() Dim source = <![CDATA[ Class Test Sub M() Dim x = 1'BIND:"= 1" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForEqualsValueVariableInitializerWithMultipleLocals() Dim source = <![CDATA[ Class Test Sub M() Dim x, y = 1'BIND:"= 1" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'x'. Dim x, y = 1'BIND:"= 1" ~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Dim x, y = 1'BIND:"= 1" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForEqualsValueVariableDeclarationWithMultipleLocals() Dim source = <![CDATA[ Class Test Sub M() Dim x, y = 1'BIND:"Dim x, y = 1" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim x, y = 1') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'x, y = 1') Declarators: IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x') Initializer: null IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42024: Unused local variable: 'x'. Dim x, y = 1'BIND:"Dim x, y = 1" ~ BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier. Dim x, y = 1'BIND:"Dim x, y = 1" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForAsNewVariableInitializer() Dim source = <![CDATA[ Class Test Sub M() Dim x As New Test'BIND:"As New Test" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Test') IObjectCreationOperation (Constructor: Sub Test..ctor()) (OperationKind.ObjectCreation, Type: Test) (Syntax: 'New Test') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForAsNewVariableDeclaration() Dim source = <![CDATA[ Class Test Sub M() Dim x As New Test'BIND:"Dim x As New Test" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim x As New Test') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'x As New Test') Declarators: IVariableDeclaratorOperation (Symbol: x As Test) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Test') IObjectCreationOperation (Constructor: Sub Test..ctor()) (OperationKind.ObjectCreation, Type: Test) (Syntax: 'New Test') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForAsNewVariableInitializerWithMultipleLocals() Dim source = <![CDATA[ Class Test Sub M() Dim x, y As New Test'BIND:"As New Test" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Test') IObjectCreationOperation (Constructor: Sub Test..ctor()) (OperationKind.ObjectCreation, Type: Test) (Syntax: 'New Test') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub TestGetOperationForAsNewVariableDeclarationWithMultipleLocals() Dim source = <![CDATA[ Class Test Sub M() Dim x, y As New Test'BIND:"x, y As New Test" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'x, y As New Test') Declarators: IVariableDeclaratorOperation (Symbol: x As Test) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null IVariableDeclaratorOperation (Symbol: y As Test) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New Test') IObjectCreationOperation (Constructor: Sub Test..ctor()) (OperationKind.ObjectCreation, Type: Test) (Syntax: 'New Test') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub #End Region #Region "Control Flow Graph" <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_01() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim a As Integer = 1 Dim b = 2 Dim c = 3, d = 4 Dim e, f As New Integer() End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32] [b As System.Int32] [c As System.Int32] [d As System.Int32] [e As System.Int32] [f As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (6) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a As Integer = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 2') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'c = 3') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd = 4') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e, f As New Integer()') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e') Right: IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer()') Arguments(0) Initializer: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e, f As New Integer()') Left: ILocalReferenceOperation: f (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'f') Right: IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer()') Arguments(0) Initializer: null Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_02() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim a As Integer a = 1 End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_03() Dim source = <![CDATA[ Imports System Public Class C Public Sub M(a As Boolean, b As Integer, c As Integer)'BIND:"Public Sub M(a As Boolean, b As Integer, c As Integer)" Dim d As Integer = If(a, b, c) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [d As System.Int32] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd As Intege ... If(a, b, c)') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b, c)') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_04() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim d As Integer = End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30201: Expression expected. Dim d As Integer = ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [d As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'd As Integer =') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_05() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim d As New End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. Dim d As New ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [d As ?] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'd As New') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: ?, IsImplicit) (Syntax: 'd') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'New') Children(0) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_06() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" #Disable Warning BC42099 ' Unused local constant Const a As Integer = 1 Static b As Integer = 1 End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32] [b As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a As Integer = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IStaticLocalInitializationSemaphoreOperation (Local Symbol: b As System.Int32) (OperationKind.StaticLocalInitializationSemaphore, Type: System.Boolean, IsImplicit) (Syntax: 'b') Leaving: {R1} Next (Regular) Block[B2] Entering: {R2} .static initializer {R2} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b As Integer = 1') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_06_WithControlFlow() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" #Disable Warning BC42099 ' Unused local constant Const a As Integer = If(True, 1, 2) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block [UnReachable] Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a As Intege ... True, 1, 2)') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'a') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(True, 1, 2)') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_07() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim a(10) As Integer End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32()] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32(), IsImplicit) (Syntax: 'a(10)') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32(), IsImplicit) (Syntax: 'a(10)') Right: IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'a(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_08() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim a(10) As Integer = 1 End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds. Dim a(10) As Integer = 1 ~~~~~ BC30311: Value of type 'Integer' cannot be converted to 'Integer()'. Dim a(10) As Integer = 1 ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32()] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10) As Integer = 1') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10)') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10) As Integer = 1') Children(2): IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsInvalid, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10, IsInvalid) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '10') Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_09() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" Dim a(10) As New Integer() End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30053: Arrays cannot be declared with 'New'. Dim a(10) As New Integer() ~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Int32()] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10) As New Integer()') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32(), IsImplicit) (Syntax: 'a(10)') Right: IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'a(10) As New Integer()') Children(2): IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'a(10)') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 11, IsImplicit) (Syntax: '10') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '10') Initializer: null IInvalidOperation (OperationKind.Invalid, Type: System.Int32(), IsInvalid, IsImplicit) (Syntax: 'As New Integer()') Children(1): IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32, IsInvalid) (Syntax: 'New Integer()') Arguments(0) Initializer: null Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_10() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" #Disable Warning BC42024 ' Unused local variable Dim = 1 Dim As New Integer() End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30203: Identifier expected. Dim = 1 ~ BC30183: Keyword is not valid as an identifier. Dim As New Integer() ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [ As System.Int32] [[As] As System.Object] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= 1') Left: ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_11() Dim source = <![CDATA[ Imports System Public Class C Public Sub M(a As Boolean, b As Integer, c As Integer)'BIND:"Public Sub M(a As Boolean, b As Integer, c As Integer)" Dim d As Integer = b, e As Integer = If(a, b, c) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [d As System.Int32] [e As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'd As Integer = b') Left: ILocalReferenceOperation: d (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'd') Right: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'e As Intege ... If(a, b, c)') Left: ILocalReferenceOperation: e (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'e') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b, c)') Next (Regular) Block[B6] Leaving: {R2} {R1} } } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_12() Dim source = <![CDATA[ Imports System Public Class C Public Sub M()'BIND:"Public Sub M()" #Disable Warning BC42024 ' Unused local variable a = 1 Dim a End Sub End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC32000: Local variable 'a' cannot be referred to before it is declared. a = 1 ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [a As System.Object] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a = 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'a = 1') Left: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: ?, IsInvalid) (Syntax: 'a') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_13() Dim source = <![CDATA[ Imports System Class C Public Property A As Object Public Property B As Object Public Sub M(b As Boolean)'BIND:"Public Sub M(b As Boolean)" Static m As Integer = If(b, 1, 2) Console.WriteLine(m) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [m As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B6] IStaticLocalInitializationSemaphoreOperation (Local Symbol: m As System.Int32) (OperationKind.StaticLocalInitializationSemaphore, Type: System.Boolean, IsImplicit) (Syntax: 'm') Next (Regular) Block[B2] Entering: {R2} .static initializer {R2} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'm As Intege ... If(b, 1, 2)') Left: ILocalReferenceOperation: m (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'm') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 1, 2)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B1] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(m)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(m)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'm') ILocalReferenceOperation: m (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'm') InConversion: CommonConversion (Exists: True, 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[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_14() Dim source = <![CDATA[ Imports System Class C Public Property A As Object Public Property B As Object Public Sub M(b As Boolean)'BIND:"Public Sub M(b As Boolean)" Static m As Integer Console.WriteLine(m) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [m As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(m)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(m)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'm') ILocalReferenceOperation: m (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'm') InConversion: CommonConversion (Exists: True, 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] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_15() Dim source = <![CDATA[ Imports System Class C Public Property A As Object Public Property B As Object Public Sub M(b As Boolean)'BIND:"Public Sub M(b As Boolean)" Console.WriteLine(b) Static m As Integer = 1 Console.WriteLine(m) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [m As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(b)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Boolean)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Jump if False (Regular) to Block[B3] IStaticLocalInitializationSemaphoreOperation (Local Symbol: m As System.Int32) (OperationKind.StaticLocalInitializationSemaphore, Type: System.Boolean, IsImplicit) (Syntax: 'm') Next (Regular) Block[B2] Entering: {R2} .static initializer {R2} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'm As Integer = 1') Left: ILocalReferenceOperation: m (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'm') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(m)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(m)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'm') ILocalReferenceOperation: m (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'm') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub VariableDeclaration_16() Dim source = <![CDATA[ Imports System Class C Public Sub M(b As Boolean)'BIND:"Public Sub M(b As Boolean)" Static m1 As Integer = 1 Static m2 As Integer = 1 Console.WriteLine(m1) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [m1 As System.Int32] [m2 As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IStaticLocalInitializationSemaphoreOperation (Local Symbol: m1 As System.Int32) (OperationKind.StaticLocalInitializationSemaphore, Type: System.Boolean, IsImplicit) (Syntax: 'm1') Next (Regular) Block[B2] Entering: {R2} .static initializer {R2} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'm1 As Integer = 1') Left: ILocalReferenceOperation: m1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'm1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] [B2] Statements (0) Jump if False (Regular) to Block[B5] IStaticLocalInitializationSemaphoreOperation (Local Symbol: m2 As System.Int32) (OperationKind.StaticLocalInitializationSemaphore, Type: System.Boolean, IsImplicit) (Syntax: 'm2') Next (Regular) Block[B4] Entering: {R3} .static initializer {R3} { Block[B4] - Block Predecessors: [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'm2 As Integer = 1') Left: ILocalReferenceOperation: m2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'm2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B5] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(m1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(m1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'm1') ILocalReferenceOperation: m1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'm1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/VisualStudio/Core/Impl/CodeModel/Collections/ExternalNamespaceCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class ExternalNamespaceCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, ProjectId projectId, INamespaceSymbol namespaceSymbol) { var collection = new ExternalNamespaceCollection(state, parent, projectId, namespaceSymbol); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ProjectId _projectId; private readonly SymbolKey _namespaceSymbolId; private ImmutableArray<EnvDTE.CodeElement> _children; internal ExternalNamespaceCollection(CodeModelState state, object parent, ProjectId projectId, INamespaceSymbol namespaceSymbol) : base(state, parent) { _projectId = projectId; _namespaceSymbolId = namespaceSymbol.GetSymbolKey(); } private ImmutableArray<EnvDTE.CodeElement> GetChildren() { if (_children == null) { var childrenBuilder = ArrayBuilder<EnvDTE.CodeElement>.GetInstance(); foreach (var child in ExternalNamespaceEnumerator.ChildrenOfNamespace(this.State, _projectId, _namespaceSymbolId)) { childrenBuilder.Add(child); } _children = childrenBuilder.ToImmutableAndFree(); } return _children; } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var children = GetChildren(); if (index < children.Length) { element = children[index]; return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var children = GetChildren(); var index = children.IndexOf(e => e.Name == name); if (index < children.Length) { element = children[index]; return true; } element = null; return false; } public override int Count { get { return GetChildren().Length; } } public override System.Collections.IEnumerator GetEnumerator() => ExternalNamespaceEnumerator.Create(this.State, _projectId, _namespaceSymbolId); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class ExternalNamespaceCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, ProjectId projectId, INamespaceSymbol namespaceSymbol) { var collection = new ExternalNamespaceCollection(state, parent, projectId, namespaceSymbol); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ProjectId _projectId; private readonly SymbolKey _namespaceSymbolId; private ImmutableArray<EnvDTE.CodeElement> _children; internal ExternalNamespaceCollection(CodeModelState state, object parent, ProjectId projectId, INamespaceSymbol namespaceSymbol) : base(state, parent) { _projectId = projectId; _namespaceSymbolId = namespaceSymbol.GetSymbolKey(); } private ImmutableArray<EnvDTE.CodeElement> GetChildren() { if (_children == null) { var childrenBuilder = ArrayBuilder<EnvDTE.CodeElement>.GetInstance(); foreach (var child in ExternalNamespaceEnumerator.ChildrenOfNamespace(this.State, _projectId, _namespaceSymbolId)) { childrenBuilder.Add(child); } _children = childrenBuilder.ToImmutableAndFree(); } return _children; } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var children = GetChildren(); if (index < children.Length) { element = children[index]; return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var children = GetChildren(); var index = children.IndexOf(e => e.Name == name); if (index < children.Length) { element = children[index]; return true; } element = null; return false; } public override int Count { get { return GetChildren().Length; } } public override System.Collections.IEnumerator GetEnumerator() => ExternalNamespaceEnumerator.Create(this.State, _projectId, _namespaceSymbolId); } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/EditorFeatures/DiagnosticsTestUtilities/Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Test.Utilities</RootNamespace> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj"> <Aliases>global,WORKSPACES</Aliases> </ProjectReference> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServer.Protocol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> </ItemGroup> <ItemGroup> <!-- TODO: Remove the below IVTs to CodeStyle Unit test projects once all analyzer/code fix tests are switched to Microsoft.CodeAnalysis.Testing --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Test.Utilities</RootNamespace> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj"> <Aliases>global,WORKSPACES</Aliases> </ProjectReference> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServer.Protocol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> </ItemGroup> <ItemGroup> <!-- TODO: Remove the below IVTs to CodeStyle Unit test projects once all analyzer/code fix tests are switched to Microsoft.CodeAnalysis.Testing --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/CSharp/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.AllInOne.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class DiagnosticAnalyzerTests { [Fact] public void DiagnosticAnalyzerAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers/attributes. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); // Add nodes that are not yet in AllInOneCSharpCode to this list. var missingSyntaxKinds = new HashSet<SyntaxKind>(); // https://github.com/dotnet/roslyn/issues/44682 Add to all in one missingSyntaxKinds.Add(SyntaxKind.WithExpression); missingSyntaxKinds.Add(SyntaxKind.RecordDeclaration); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { analyzer }, options); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(missingSyntaxKinds); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks); } [WorkItem(896075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/896075")] [Fact] public void DiagnosticAnalyzerIndexerDeclaration() { var source = @" public class C { public string this[int index] { get { return string.Empty; } set { value = value + string.Empty; } } } "; CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } // AllInOne does not include experimental features. #region Experimental Features [Fact] public void DiagnosticAnalyzerConditionalAccess() { var source = @" public class C { public string this[int index] { get { return string.Empty ?. ToString() ?[1] .ToString() ; } set { value = value + string.Empty; } } } "; CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } [Fact] public void DiagnosticAnalyzerExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" public class C { public int P => 10; }").VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } #endregion [Fact] [WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")] public void AnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var compilation = CreateCompilationWithMscorlib45(TestResource.AllInOneCSharpCode); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptions(analyzer => compilation.GetAnalyzerDiagnostics(new[] { analyzer }, options)); } [Fact] public void AnalyzerOptionsArePassedToAllAnalyzers() { var text = new StringText(string.Empty, encodingOpt: null); AnalyzerOptions options = new AnalyzerOptions ( new[] { new TestAdditionalText("myfilepath", text) }.ToImmutableArray<AdditionalText>() ); var compilation = CreateCompilationWithMscorlib45(TestResource.AllInOneCSharpCode); var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(options); compilation.GetAnalyzerDiagnostics(new[] { analyzer }, options); analyzer.VerifyAnalyzerOptions(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class DiagnosticAnalyzerTests { [Fact] public void DiagnosticAnalyzerAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers/attributes. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); // Add nodes that are not yet in AllInOneCSharpCode to this list. var missingSyntaxKinds = new HashSet<SyntaxKind>(); // https://github.com/dotnet/roslyn/issues/44682 Add to all in one missingSyntaxKinds.Add(SyntaxKind.WithExpression); missingSyntaxKinds.Add(SyntaxKind.RecordDeclaration); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { analyzer }, options); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(missingSyntaxKinds); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks); } [WorkItem(896075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/896075")] [Fact] public void DiagnosticAnalyzerIndexerDeclaration() { var source = @" public class C { public string this[int index] { get { return string.Empty; } set { value = value + string.Empty; } } } "; CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } // AllInOne does not include experimental features. #region Experimental Features [Fact] public void DiagnosticAnalyzerConditionalAccess() { var source = @" public class C { public string this[int index] { get { return string.Empty ?. ToString() ?[1] .ToString() ; } set { value = value + string.Empty; } } } "; CreateCompilationWithMscorlib45(source).VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } [Fact] public void DiagnosticAnalyzerExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" public class C { public int P => 10; }").VerifyAnalyzerDiagnostics(new[] { new CSharpTrackingDiagnosticAnalyzer() }); } #endregion [Fact] [WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")] public void AnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var compilation = CreateCompilationWithMscorlib45(TestResource.AllInOneCSharpCode); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptions(analyzer => compilation.GetAnalyzerDiagnostics(new[] { analyzer }, options)); } [Fact] public void AnalyzerOptionsArePassedToAllAnalyzers() { var text = new StringText(string.Empty, encodingOpt: null); AnalyzerOptions options = new AnalyzerOptions ( new[] { new TestAdditionalText("myfilepath", text) }.ToImmutableArray<AdditionalText>() ); var compilation = CreateCompilationWithMscorlib45(TestResource.AllInOneCSharpCode); var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(options); compilation.GetAnalyzerDiagnostics(new[] { analyzer }, options); analyzer.VerifyAnalyzerOptions(); } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Workspaces/VisualBasic/Portable/Utilities/IntrinsicOperators/GetTypeExpressionDocumentation.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.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Friend NotInheritable Class GetTypeExpressionDocumentation Inherits AbstractIntrinsicOperatorDocumentation Public Overrides Function GetParameterDocumentation(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.The_type_name_to_return_a_System_Type_object_for Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides Function GetParameterName(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.typeName Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides ReadOnly Property ParameterCount As Integer Get Return 1 End Get End Property Public Overrides ReadOnly Property DocumentationText As String Get Return VBWorkspaceResources.Returns_a_System_Type_object_for_the_specified_type_name End Get End Property Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart) Get Return { New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "GetType"), New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(") } End Get End Property Public Overrides ReadOnly Property IncludeAsType As Boolean Get Return True End Get End Property Public Overrides Function TryGetTypeNameParameter(syntaxNode As SyntaxNode, index As Integer) As TypeSyntax Dim getTypeExpression = TryCast(syntaxNode, GetTypeExpressionSyntax) If getTypeExpression IsNot Nothing Then Return getTypeExpression.Type Else Return Nothing End If End Function Public Overrides ReadOnly Property ReturnTypeMetadataName As String Get Return "System.Type" 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 Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Friend NotInheritable Class GetTypeExpressionDocumentation Inherits AbstractIntrinsicOperatorDocumentation Public Overrides Function GetParameterDocumentation(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.The_type_name_to_return_a_System_Type_object_for Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides Function GetParameterName(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.typeName Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides ReadOnly Property ParameterCount As Integer Get Return 1 End Get End Property Public Overrides ReadOnly Property DocumentationText As String Get Return VBWorkspaceResources.Returns_a_System_Type_object_for_the_specified_type_name End Get End Property Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart) Get Return { New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "GetType"), New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(") } End Get End Property Public Overrides ReadOnly Property IncludeAsType As Boolean Get Return True End Get End Property Public Overrides Function TryGetTypeNameParameter(syntaxNode As SyntaxNode, index As Integer) As TypeSyntax Dim getTypeExpression = TryCast(syntaxNode, GetTypeExpressionSyntax) If getTypeExpression IsNot Nothing Then Return getTypeExpression.Type Else Return Nothing End If End Function Public Overrides ReadOnly Property ReturnTypeMetadataName As String Get Return "System.Type" End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/EditorFeatures/VisualBasic/BraceMatching/OpenCloseParenBraceMatcher.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.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.BraceMatching <ExportBraceMatcher(LanguageNames.VisualBasic)> Friend Class OpenCloseParenBraceMatcher Inherits AbstractVisualBasicBraceMatcher <ImportingConstructor()> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.BraceMatching <ExportBraceMatcher(LanguageNames.VisualBasic)> Friend Class OpenCloseParenBraceMatcher Inherits AbstractVisualBasicBraceMatcher <ImportingConstructor()> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken) End Sub End Class End Namespace
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Workspaces/CoreTestUtilities/TestExportJoinableTaskContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ComponentModel.Composition; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Threading; using Xunit.Sdk; namespace Microsoft.CodeAnalysis.Test.Utilities { // Starting with 15.3 the editor took a dependency on JoinableTaskContext // in Text.Logic and IntelliSense layers as an editor host provided service. [Export] internal partial class TestExportJoinableTaskContext { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestExportJoinableTaskContext() { var synchronizationContext = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(GetEffectiveSynchronizationContext()); (JoinableTaskContext, SynchronizationContext) = CreateJoinableTaskContext(); ResetThreadAffinity(JoinableTaskContext.Factory); } finally { SynchronizationContext.SetSynchronizationContext(synchronizationContext); } } private static (JoinableTaskContext joinableTaskContext, SynchronizationContext synchronizationContext) CreateJoinableTaskContext() { Thread mainThread; SynchronizationContext synchronizationContext; if (SynchronizationContext.Current is DispatcherSynchronizationContext) { // The current thread is the main thread, and provides a suitable synchronization context mainThread = Thread.CurrentThread; synchronizationContext = SynchronizationContext.Current; } else { // The current thread is not known to be the main thread; we have no way to know if the // synchronization context of the current thread will behave in a manner consistent with main thread // synchronization contexts, so we use DenyExecutionSynchronizationContext to track any attempted // use of it. var denyExecutionSynchronizationContext = new DenyExecutionSynchronizationContext(SynchronizationContext.Current); mainThread = denyExecutionSynchronizationContext.MainThread; synchronizationContext = denyExecutionSynchronizationContext; } return (new JoinableTaskContext(mainThread, synchronizationContext), synchronizationContext); } [Export] private JoinableTaskContext JoinableTaskContext { get; } internal SynchronizationContext SynchronizationContext { get; } internal static SynchronizationContext? GetEffectiveSynchronizationContext() { if (SynchronizationContext.Current is AsyncTestSyncContext asyncTestSyncContext) { SynchronizationContext? innerSynchronizationContext = null; asyncTestSyncContext.Send( _ => { innerSynchronizationContext = SynchronizationContext.Current; }, null); return innerSynchronizationContext; } else { return SynchronizationContext.Current; } } /// <summary> /// Reset the thread affinity, in particular the designated foreground thread, to the active /// thread. /// </summary> internal static void ResetThreadAffinity(JoinableTaskFactory joinableTaskFactory) { // HACK: When the platform team took over several of our components they created a copy // of ForegroundThreadAffinitizedObject. This needs to be reset in the same way as our copy // does. Reflection is the only choice at the moment. var thread = joinableTaskFactory.Context.MainThread; var taskScheduler = new JoinableTaskFactoryTaskScheduler(joinableTaskFactory); foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { var type = assembly.GetType("Microsoft.VisualStudio.Language.Intellisense.Implementation.ForegroundThreadAffinitizedObject", throwOnError: false); if (type != null) { type.GetField("foregroundThread", BindingFlags.Static | BindingFlags.NonPublic)!.SetValue(null, thread); type.GetField("ForegroundTaskScheduler", BindingFlags.Static | BindingFlags.NonPublic)!.SetValue(null, taskScheduler); break; } } } // HACK: Part of ResetThreadAffinity private class JoinableTaskFactoryTaskScheduler : TaskScheduler { private readonly JoinableTaskFactory _joinableTaskFactory; public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory) => _joinableTaskFactory = joinableTaskFactory; public override int MaximumConcurrencyLevel => 1; protected override IEnumerable<Task>? GetScheduledTasks() => null; protected override void QueueTask(Task task) { _joinableTaskFactory.RunAsync(async () => { await _joinableTaskFactory.SwitchToMainThreadAsync(); TryExecuteTask(task); }); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (_joinableTaskFactory.Context.IsOnMainThread) { return TryExecuteTask(task); } 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.ComponentModel.Composition; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Threading; using Xunit.Sdk; namespace Microsoft.CodeAnalysis.Test.Utilities { // Starting with 15.3 the editor took a dependency on JoinableTaskContext // in Text.Logic and IntelliSense layers as an editor host provided service. [Export] internal partial class TestExportJoinableTaskContext { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestExportJoinableTaskContext() { var synchronizationContext = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(GetEffectiveSynchronizationContext()); (JoinableTaskContext, SynchronizationContext) = CreateJoinableTaskContext(); ResetThreadAffinity(JoinableTaskContext.Factory); } finally { SynchronizationContext.SetSynchronizationContext(synchronizationContext); } } private static (JoinableTaskContext joinableTaskContext, SynchronizationContext synchronizationContext) CreateJoinableTaskContext() { Thread mainThread; SynchronizationContext synchronizationContext; if (SynchronizationContext.Current is DispatcherSynchronizationContext) { // The current thread is the main thread, and provides a suitable synchronization context mainThread = Thread.CurrentThread; synchronizationContext = SynchronizationContext.Current; } else { // The current thread is not known to be the main thread; we have no way to know if the // synchronization context of the current thread will behave in a manner consistent with main thread // synchronization contexts, so we use DenyExecutionSynchronizationContext to track any attempted // use of it. var denyExecutionSynchronizationContext = new DenyExecutionSynchronizationContext(SynchronizationContext.Current); mainThread = denyExecutionSynchronizationContext.MainThread; synchronizationContext = denyExecutionSynchronizationContext; } return (new JoinableTaskContext(mainThread, synchronizationContext), synchronizationContext); } [Export] private JoinableTaskContext JoinableTaskContext { get; } internal SynchronizationContext SynchronizationContext { get; } internal static SynchronizationContext? GetEffectiveSynchronizationContext() { if (SynchronizationContext.Current is AsyncTestSyncContext asyncTestSyncContext) { SynchronizationContext? innerSynchronizationContext = null; asyncTestSyncContext.Send( _ => { innerSynchronizationContext = SynchronizationContext.Current; }, null); return innerSynchronizationContext; } else { return SynchronizationContext.Current; } } /// <summary> /// Reset the thread affinity, in particular the designated foreground thread, to the active /// thread. /// </summary> internal static void ResetThreadAffinity(JoinableTaskFactory joinableTaskFactory) { // HACK: When the platform team took over several of our components they created a copy // of ForegroundThreadAffinitizedObject. This needs to be reset in the same way as our copy // does. Reflection is the only choice at the moment. var thread = joinableTaskFactory.Context.MainThread; var taskScheduler = new JoinableTaskFactoryTaskScheduler(joinableTaskFactory); foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { var type = assembly.GetType("Microsoft.VisualStudio.Language.Intellisense.Implementation.ForegroundThreadAffinitizedObject", throwOnError: false); if (type != null) { type.GetField("foregroundThread", BindingFlags.Static | BindingFlags.NonPublic)!.SetValue(null, thread); type.GetField("ForegroundTaskScheduler", BindingFlags.Static | BindingFlags.NonPublic)!.SetValue(null, taskScheduler); break; } } } // HACK: Part of ResetThreadAffinity private class JoinableTaskFactoryTaskScheduler : TaskScheduler { private readonly JoinableTaskFactory _joinableTaskFactory; public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory) => _joinableTaskFactory = joinableTaskFactory; public override int MaximumConcurrencyLevel => 1; protected override IEnumerable<Task>? GetScheduledTasks() => null; protected override void QueueTask(Task task) { _joinableTaskFactory.RunAsync(async () => { await _joinableTaskFactory.SwitchToMainThreadAsync(); TryExecuteTask(task); }); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (_joinableTaskFactory.Context.IsOnMainThread) { return TryExecuteTask(task); } return false; } } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Scripting/VisualBasic/PublicAPI.Shipped.txt
Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.VisualBasicObjectFormatter Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript Overrides Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.VisualBasicObjectFormatter.FormatException(e As System.Exception) -> String Overrides Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.VisualBasicObjectFormatter.FormatObject(obj As Object, options As Microsoft.CodeAnalysis.Scripting.Hosting.PrintOptions) -> String Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.VisualBasicObjectFormatter.Instance() -> Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.VisualBasicObjectFormatter Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.Create(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globalsType As System.Type = Nothing, assemblyLoader As Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader = Nothing) -> Microsoft.CodeAnalysis.Scripting.Script(Of Object) Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.Create(Of T)(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globalsType As System.Type = Nothing, assemblyLoader As Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader = Nothing) -> Microsoft.CodeAnalysis.Scripting.Script(Of T) Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.EvaluateAsync(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globals As Object = Nothing, cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Threading.Tasks.Task(Of Object) Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.EvaluateAsync(Of T)(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globals As Object = Nothing, cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Threading.Tasks.Task(Of T) Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.RunAsync(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globals As Object = Nothing, cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Threading.Tasks.Task(Of Microsoft.CodeAnalysis.Scripting.ScriptState(Of Object)) Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.RunAsync(Of T)(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globals As Object = Nothing, cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Threading.Tasks.Task(Of Microsoft.CodeAnalysis.Scripting.ScriptState(Of T))
Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.VisualBasicObjectFormatter Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript Overrides Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.VisualBasicObjectFormatter.FormatException(e As System.Exception) -> String Overrides Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.VisualBasicObjectFormatter.FormatObject(obj As Object, options As Microsoft.CodeAnalysis.Scripting.Hosting.PrintOptions) -> String Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.VisualBasicObjectFormatter.Instance() -> Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting.VisualBasicObjectFormatter Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.Create(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globalsType As System.Type = Nothing, assemblyLoader As Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader = Nothing) -> Microsoft.CodeAnalysis.Scripting.Script(Of Object) Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.Create(Of T)(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globalsType As System.Type = Nothing, assemblyLoader As Microsoft.CodeAnalysis.Scripting.Hosting.InteractiveAssemblyLoader = Nothing) -> Microsoft.CodeAnalysis.Scripting.Script(Of T) Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.EvaluateAsync(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globals As Object = Nothing, cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Threading.Tasks.Task(Of Object) Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.EvaluateAsync(Of T)(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globals As Object = Nothing, cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Threading.Tasks.Task(Of T) Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.RunAsync(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globals As Object = Nothing, cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Threading.Tasks.Task(Of Microsoft.CodeAnalysis.Scripting.ScriptState(Of Object)) Shared Microsoft.CodeAnalysis.VisualBasic.Scripting.VisualBasicScript.RunAsync(Of T)(code As String, options As Microsoft.CodeAnalysis.Scripting.ScriptOptions = Nothing, globals As Object = Nothing, cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Threading.Tasks.Task(Of Microsoft.CodeAnalysis.Scripting.ScriptState(Of T))
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/Test/Resources/Core/DiagnosticTests/ErrTestLib02.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace NS { // for CS1714 public class E<T> : D<T> { } public class Ref { public static A GetA() { return new A(); } // for CS1682 - nested public static A.B GetB() { return null; } // for CS1684 public static C GetC() { return null; } // for CS1714 public static E<int> GetE() { return null; } } } namespace N1 { public class N2 { public class A { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace NS { // for CS1714 public class E<T> : D<T> { } public class Ref { public static A GetA() { return new A(); } // for CS1682 - nested public static A.B GetB() { return null; } // for CS1684 public static C GetC() { return null; } // for CS1714 public static E<int> GetE() { return null; } } } namespace N1 { public class N2 { public class A { } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Workspaces/CoreTest/UtilityTest/ExceptionHelpersTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.ErrorReporting; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class ExceptionHelpersTests : TestBase { /// <summary> /// Test that throwing OperationCanceledException does NOT trigger FailFast /// </summary> [Fact] public void TestExecuteWithErrorReportingThrowOperationCanceledException() { var finallyExecuted = false; void a() { try { throw new OperationCanceledException(); } finally { finallyExecuted = true; } } try { try { a(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } Assert.True(false, "Should not get here because an exception should be thrown before this point."); } catch (OperationCanceledException) { Assert.True(finallyExecuted); return; } Assert.True(false, "Should have returned in the catch block before this point."); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.ErrorReporting; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class ExceptionHelpersTests : TestBase { /// <summary> /// Test that throwing OperationCanceledException does NOT trigger FailFast /// </summary> [Fact] public void TestExecuteWithErrorReportingThrowOperationCanceledException() { var finallyExecuted = false; void a() { try { throw new OperationCanceledException(); } finally { finallyExecuted = true; } } try { try { a(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } Assert.True(false, "Should not get here because an exception should be thrown before this point."); } catch (OperationCanceledException) { Assert.True(finallyExecuted); return; } Assert.True(false, "Should have returned in the catch block before this point."); } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/Core/Portable/DocumentationComments/DocumentationProvider.NullDocumentationProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; namespace Microsoft.CodeAnalysis { public partial class DocumentationProvider { /// <summary> /// A trivial DocumentationProvider which never returns documentation. /// </summary> private class NullDocumentationProvider : DocumentationProvider { protected internal override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken)) { return ""; } public override bool Equals(object? obj) { // Only one instance is expected to exist, so reference equality is fine. return (object)this == obj; } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; namespace Microsoft.CodeAnalysis { public partial class DocumentationProvider { /// <summary> /// A trivial DocumentationProvider which never returns documentation. /// </summary> private class NullDocumentationProvider : DocumentationProvider { protected internal override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken)) { return ""; } public override bool Equals(object? obj) { // Only one instance is expected to exist, so reference equality is fine. return (object)this == obj; } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } } } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/Compilers/CSharp/Portable/Errors/MessageProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class MessageProvider : CommonMessageProvider, IObjectWritable { public static readonly MessageProvider Instance = new MessageProvider(); static MessageProvider() { ObjectBinder.RegisterTypeReader(typeof(MessageProvider), r => Instance); } private MessageProvider() { } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { // write nothing, always read/deserialized as global Instance } public override DiagnosticSeverity GetSeverity(int code) { return ErrorFacts.GetSeverity((ErrorCode)code); } public override string LoadMessage(int code, CultureInfo language) { return ErrorFacts.GetMessage((ErrorCode)code, language); } public override LocalizableString GetMessageFormat(int code) { return ErrorFacts.GetMessageFormat((ErrorCode)code); } public override LocalizableString GetDescription(int code) { return ErrorFacts.GetDescription((ErrorCode)code); } public override LocalizableString GetTitle(int code) { return ErrorFacts.GetTitle((ErrorCode)code); } public override string GetHelpLink(int code) { return ErrorFacts.GetHelpLink((ErrorCode)code); } public override string GetCategory(int code) { return ErrorFacts.GetCategory((ErrorCode)code); } public override string CodePrefix { get { return "CS"; } } // Given a message identifier (e.g., CS0219), severity, warning as error and a culture, // get the entire prefix (e.g., "error CS0219:" for C#) used on error messages. public override string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo culture) { return String.Format(culture, "{0} {1}", severity == DiagnosticSeverity.Error || isWarningAsError ? "error" : "warning", id); } public override int GetWarningLevel(int code) { return ErrorFacts.GetWarningLevel((ErrorCode)code); } public override Type ErrorCodeType { get { return typeof(ErrorCode); } } public override Diagnostic CreateDiagnostic(int code, Location location, params object[] args) { var info = new CSDiagnosticInfo((ErrorCode)code, args, ImmutableArray<Symbol>.Empty, ImmutableArray<Location>.Empty); return new CSDiagnostic(info, location); } public override Diagnostic CreateDiagnostic(DiagnosticInfo info) { return new CSDiagnostic(info, Location.None); } public override string GetErrorDisplayString(ISymbol symbol) { // show extra info for assembly if possible such as version, public key token etc. if (symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.Namespace) { return symbol.ToString(); } return SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.CSharpShortErrorMessageFormat); } public override ReportDiagnostic GetDiagnosticReport(DiagnosticInfo diagnosticInfo, CompilationOptions options) { bool hasPragmaSuppression; return CSharpDiagnosticFilter.GetDiagnosticReport(diagnosticInfo.Severity, true, diagnosticInfo.MessageIdentifier, diagnosticInfo.WarningLevel, Location.None, diagnosticInfo.Category, options.WarningLevel, ((CSharpCompilationOptions)options).NullableContextOptions, options.GeneralDiagnosticOption, options.SpecificDiagnosticOptions, options.SyntaxTreeOptionsProvider, CancellationToken.None, // We don't have a tree so there's no need to pass cancellation to the SyntaxTreeOptionsProvider out hasPragmaSuppression); } public override int ERR_FailedToCreateTempFile => (int)ErrorCode.ERR_CantMakeTempFile; public override int ERR_MultipleAnalyzerConfigsInSameDir => (int)ErrorCode.ERR_MultipleAnalyzerConfigsInSameDir; // command line: public override int ERR_ExpectedSingleScript => (int)ErrorCode.ERR_ExpectedSingleScript; public override int ERR_OpenResponseFile => (int)ErrorCode.ERR_OpenResponseFile; public override int ERR_InvalidPathMap => (int)ErrorCode.ERR_InvalidPathMap; public override int FTL_InvalidInputFileName => (int)ErrorCode.FTL_InvalidInputFileName; public override int ERR_FileNotFound => (int)ErrorCode.ERR_FileNotFound; public override int ERR_NoSourceFile => (int)ErrorCode.ERR_NoSourceFile; public override int ERR_CantOpenFileWrite => (int)ErrorCode.ERR_CantOpenFileWrite; public override int ERR_OutputWriteFailed => (int)ErrorCode.ERR_OutputWriteFailed; public override int WRN_NoConfigNotOnCommandLine => (int)ErrorCode.WRN_NoConfigNotOnCommandLine; public override int ERR_BinaryFile => (int)ErrorCode.ERR_BinaryFile; public override int WRN_AnalyzerCannotBeCreated => (int)ErrorCode.WRN_AnalyzerCannotBeCreated; public override int WRN_NoAnalyzerInAssembly => (int)ErrorCode.WRN_NoAnalyzerInAssembly; public override int WRN_UnableToLoadAnalyzer => (int)ErrorCode.WRN_UnableToLoadAnalyzer; public override int WRN_AnalyzerReferencesFramework => (int)ErrorCode.WRN_AnalyzerReferencesFramework; public override int INF_UnableToLoadSomeTypesInAnalyzer => (int)ErrorCode.INF_UnableToLoadSomeTypesInAnalyzer; public override int ERR_CantReadRulesetFile => (int)ErrorCode.ERR_CantReadRulesetFile; public override int ERR_CompileCancelled => (int)ErrorCode.ERR_CompileCancelled; // parse options: public override int ERR_BadSourceCodeKind => (int)ErrorCode.ERR_BadSourceCodeKind; public override int ERR_BadDocumentationMode => (int)ErrorCode.ERR_BadDocumentationMode; // compilation options: public override int ERR_BadCompilationOptionValue => (int)ErrorCode.ERR_BadCompilationOptionValue; public override int ERR_MutuallyExclusiveOptions => (int)ErrorCode.ERR_MutuallyExclusiveOptions; // emit options: public override int ERR_InvalidDebugInformationFormat => (int)ErrorCode.ERR_InvalidDebugInformationFormat; public override int ERR_InvalidOutputName => (int)ErrorCode.ERR_InvalidOutputName; public override int ERR_InvalidFileAlignment => (int)ErrorCode.ERR_InvalidFileAlignment; public override int ERR_InvalidSubsystemVersion => (int)ErrorCode.ERR_InvalidSubsystemVersion; public override int ERR_InvalidInstrumentationKind => (int)ErrorCode.ERR_InvalidInstrumentationKind; public override int ERR_InvalidHashAlgorithmName => (int)ErrorCode.ERR_InvalidHashAlgorithmName; // reference manager: public override int ERR_MetadataFileNotAssembly => (int)ErrorCode.ERR_ImportNonAssembly; public override int ERR_MetadataFileNotModule => (int)ErrorCode.ERR_AddModuleAssembly; public override int ERR_InvalidAssemblyMetadata => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_InvalidModuleMetadata => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_ErrorOpeningAssemblyFile => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_ErrorOpeningModuleFile => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_MetadataFileNotFound => (int)ErrorCode.ERR_NoMetadataFile; public override int ERR_MetadataReferencesNotSupported => (int)ErrorCode.ERR_MetadataReferencesNotSupported; public override int ERR_LinkedNetmoduleMetadataMustProvideFullPEImage => (int)ErrorCode.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage; public override void ReportDuplicateMetadataReferenceStrong(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) { diagnostics.Add(ErrorCode.ERR_DuplicateImport, location, reference.Display ?? identity.GetDisplayName(), equivalentReference.Display ?? equivalentIdentity.GetDisplayName()); } public override void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) { diagnostics.Add(ErrorCode.ERR_DuplicateImportSimple, location, identity.Name, reference.Display ?? identity.GetDisplayName()); } // signing: public override int ERR_PublicKeyFileFailure => (int)ErrorCode.ERR_PublicKeyFileFailure; public override int ERR_PublicKeyContainerFailure => (int)ErrorCode.ERR_PublicKeyContainerFailure; public override int ERR_OptionMustBeAbsolutePath => (int)ErrorCode.ERR_OptionMustBeAbsolutePath; // resources: public override int ERR_CantReadResource => (int)ErrorCode.ERR_CantReadResource; public override int ERR_CantOpenWin32Resource => (int)ErrorCode.ERR_CantOpenWin32Res; public override int ERR_CantOpenWin32Manifest => (int)ErrorCode.ERR_CantOpenWin32Manifest; public override int ERR_CantOpenWin32Icon => (int)ErrorCode.ERR_CantOpenIcon; public override int ERR_ErrorBuildingWin32Resource => (int)ErrorCode.ERR_ErrorBuildingWin32Resources; public override int ERR_BadWin32Resource => (int)ErrorCode.ERR_BadWin32Res; public override int ERR_ResourceFileNameNotUnique => (int)ErrorCode.ERR_ResourceFileNameNotUnique; public override int ERR_ResourceNotUnique => (int)ErrorCode.ERR_ResourceNotUnique; public override int ERR_ResourceInModule => (int)ErrorCode.ERR_CantRefResource; // pseudo-custom attributes: public override int ERR_PermissionSetAttributeFileReadError => (int)ErrorCode.ERR_PermissionSetAttributeFileReadError; // PDB Writer: public override int ERR_EncodinglessSyntaxTree => (int)ErrorCode.ERR_EncodinglessSyntaxTree; public override int WRN_PdbUsingNameTooLong => (int)ErrorCode.WRN_DebugFullNameTooLong; public override int WRN_PdbLocalNameTooLong => (int)ErrorCode.WRN_PdbLocalNameTooLong; public override int ERR_PdbWritingFailed => (int)ErrorCode.FTL_DebugEmitFailure; // PE Writer: public override int ERR_MetadataNameTooLong => (int)ErrorCode.ERR_MetadataNameTooLong; public override int ERR_EncReferenceToAddedMember => (int)ErrorCode.ERR_EncReferenceToAddedMember; public override int ERR_TooManyUserStrings => (int)ErrorCode.ERR_TooManyUserStrings; public override int ERR_PeWritingFailure => (int)ErrorCode.ERR_PeWritingFailure; public override int ERR_ModuleEmitFailure => (int)ErrorCode.ERR_ModuleEmitFailure; public override int ERR_EncUpdateFailedMissingAttribute => (int)ErrorCode.ERR_EncUpdateFailedMissingAttribute; public override int ERR_InvalidDebugInfo => (int)ErrorCode.ERR_InvalidDebugInfo; // Generators: public override int WRN_GeneratorFailedDuringInitialization => (int)ErrorCode.WRN_GeneratorFailedDuringInitialization; public override int WRN_GeneratorFailedDuringGeneration => (int)ErrorCode.WRN_GeneratorFailedDuringGeneration; protected override void ReportInvalidAttributeArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); } protected override void ReportInvalidNamedArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_InvalidNamedArgument, node.ArgumentList.Arguments[namedArgumentIndex].Location, parameterName); } protected override void ReportParameterNotValidForType(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_ParameterNotValidForType, node.ArgumentList.Arguments[namedArgumentIndex].Location); } protected override void ReportMarshalUnmanagedTypeNotValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeNotValidForFields, attributeArgumentSyntax.Location, unmanagedTypeName); } protected override void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, attributeArgumentSyntax.Location, unmanagedTypeName); } protected override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired1, node.Name.Location, parameterName); } protected override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired2, node.Name.Location, parameterName1, parameterName2); } public override int ERR_BadAssemblyName => (int)ErrorCode.ERR_BadAssemblyName; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class MessageProvider : CommonMessageProvider, IObjectWritable { public static readonly MessageProvider Instance = new MessageProvider(); static MessageProvider() { ObjectBinder.RegisterTypeReader(typeof(MessageProvider), r => Instance); } private MessageProvider() { } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { // write nothing, always read/deserialized as global Instance } public override DiagnosticSeverity GetSeverity(int code) { return ErrorFacts.GetSeverity((ErrorCode)code); } public override string LoadMessage(int code, CultureInfo language) { return ErrorFacts.GetMessage((ErrorCode)code, language); } public override LocalizableString GetMessageFormat(int code) { return ErrorFacts.GetMessageFormat((ErrorCode)code); } public override LocalizableString GetDescription(int code) { return ErrorFacts.GetDescription((ErrorCode)code); } public override LocalizableString GetTitle(int code) { return ErrorFacts.GetTitle((ErrorCode)code); } public override string GetHelpLink(int code) { return ErrorFacts.GetHelpLink((ErrorCode)code); } public override string GetCategory(int code) { return ErrorFacts.GetCategory((ErrorCode)code); } public override string CodePrefix { get { return "CS"; } } // Given a message identifier (e.g., CS0219), severity, warning as error and a culture, // get the entire prefix (e.g., "error CS0219:" for C#) used on error messages. public override string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo culture) { return String.Format(culture, "{0} {1}", severity == DiagnosticSeverity.Error || isWarningAsError ? "error" : "warning", id); } public override int GetWarningLevel(int code) { return ErrorFacts.GetWarningLevel((ErrorCode)code); } public override Type ErrorCodeType { get { return typeof(ErrorCode); } } public override Diagnostic CreateDiagnostic(int code, Location location, params object[] args) { var info = new CSDiagnosticInfo((ErrorCode)code, args, ImmutableArray<Symbol>.Empty, ImmutableArray<Location>.Empty); return new CSDiagnostic(info, location); } public override Diagnostic CreateDiagnostic(DiagnosticInfo info) { return new CSDiagnostic(info, Location.None); } public override string GetErrorDisplayString(ISymbol symbol) { // show extra info for assembly if possible such as version, public key token etc. if (symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.Namespace) { return symbol.ToString(); } return SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.CSharpShortErrorMessageFormat); } public override ReportDiagnostic GetDiagnosticReport(DiagnosticInfo diagnosticInfo, CompilationOptions options) { bool hasPragmaSuppression; return CSharpDiagnosticFilter.GetDiagnosticReport(diagnosticInfo.Severity, true, diagnosticInfo.MessageIdentifier, diagnosticInfo.WarningLevel, Location.None, diagnosticInfo.Category, options.WarningLevel, ((CSharpCompilationOptions)options).NullableContextOptions, options.GeneralDiagnosticOption, options.SpecificDiagnosticOptions, options.SyntaxTreeOptionsProvider, CancellationToken.None, // We don't have a tree so there's no need to pass cancellation to the SyntaxTreeOptionsProvider out hasPragmaSuppression); } public override int ERR_FailedToCreateTempFile => (int)ErrorCode.ERR_CantMakeTempFile; public override int ERR_MultipleAnalyzerConfigsInSameDir => (int)ErrorCode.ERR_MultipleAnalyzerConfigsInSameDir; // command line: public override int ERR_ExpectedSingleScript => (int)ErrorCode.ERR_ExpectedSingleScript; public override int ERR_OpenResponseFile => (int)ErrorCode.ERR_OpenResponseFile; public override int ERR_InvalidPathMap => (int)ErrorCode.ERR_InvalidPathMap; public override int FTL_InvalidInputFileName => (int)ErrorCode.FTL_InvalidInputFileName; public override int ERR_FileNotFound => (int)ErrorCode.ERR_FileNotFound; public override int ERR_NoSourceFile => (int)ErrorCode.ERR_NoSourceFile; public override int ERR_CantOpenFileWrite => (int)ErrorCode.ERR_CantOpenFileWrite; public override int ERR_OutputWriteFailed => (int)ErrorCode.ERR_OutputWriteFailed; public override int WRN_NoConfigNotOnCommandLine => (int)ErrorCode.WRN_NoConfigNotOnCommandLine; public override int ERR_BinaryFile => (int)ErrorCode.ERR_BinaryFile; public override int WRN_AnalyzerCannotBeCreated => (int)ErrorCode.WRN_AnalyzerCannotBeCreated; public override int WRN_NoAnalyzerInAssembly => (int)ErrorCode.WRN_NoAnalyzerInAssembly; public override int WRN_UnableToLoadAnalyzer => (int)ErrorCode.WRN_UnableToLoadAnalyzer; public override int WRN_AnalyzerReferencesFramework => (int)ErrorCode.WRN_AnalyzerReferencesFramework; public override int INF_UnableToLoadSomeTypesInAnalyzer => (int)ErrorCode.INF_UnableToLoadSomeTypesInAnalyzer; public override int ERR_CantReadRulesetFile => (int)ErrorCode.ERR_CantReadRulesetFile; public override int ERR_CompileCancelled => (int)ErrorCode.ERR_CompileCancelled; // parse options: public override int ERR_BadSourceCodeKind => (int)ErrorCode.ERR_BadSourceCodeKind; public override int ERR_BadDocumentationMode => (int)ErrorCode.ERR_BadDocumentationMode; // compilation options: public override int ERR_BadCompilationOptionValue => (int)ErrorCode.ERR_BadCompilationOptionValue; public override int ERR_MutuallyExclusiveOptions => (int)ErrorCode.ERR_MutuallyExclusiveOptions; // emit options: public override int ERR_InvalidDebugInformationFormat => (int)ErrorCode.ERR_InvalidDebugInformationFormat; public override int ERR_InvalidOutputName => (int)ErrorCode.ERR_InvalidOutputName; public override int ERR_InvalidFileAlignment => (int)ErrorCode.ERR_InvalidFileAlignment; public override int ERR_InvalidSubsystemVersion => (int)ErrorCode.ERR_InvalidSubsystemVersion; public override int ERR_InvalidInstrumentationKind => (int)ErrorCode.ERR_InvalidInstrumentationKind; public override int ERR_InvalidHashAlgorithmName => (int)ErrorCode.ERR_InvalidHashAlgorithmName; // reference manager: public override int ERR_MetadataFileNotAssembly => (int)ErrorCode.ERR_ImportNonAssembly; public override int ERR_MetadataFileNotModule => (int)ErrorCode.ERR_AddModuleAssembly; public override int ERR_InvalidAssemblyMetadata => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_InvalidModuleMetadata => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_ErrorOpeningAssemblyFile => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_ErrorOpeningModuleFile => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_MetadataFileNotFound => (int)ErrorCode.ERR_NoMetadataFile; public override int ERR_MetadataReferencesNotSupported => (int)ErrorCode.ERR_MetadataReferencesNotSupported; public override int ERR_LinkedNetmoduleMetadataMustProvideFullPEImage => (int)ErrorCode.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage; public override void ReportDuplicateMetadataReferenceStrong(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) { diagnostics.Add(ErrorCode.ERR_DuplicateImport, location, reference.Display ?? identity.GetDisplayName(), equivalentReference.Display ?? equivalentIdentity.GetDisplayName()); } public override void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) { diagnostics.Add(ErrorCode.ERR_DuplicateImportSimple, location, identity.Name, reference.Display ?? identity.GetDisplayName()); } // signing: public override int ERR_PublicKeyFileFailure => (int)ErrorCode.ERR_PublicKeyFileFailure; public override int ERR_PublicKeyContainerFailure => (int)ErrorCode.ERR_PublicKeyContainerFailure; public override int ERR_OptionMustBeAbsolutePath => (int)ErrorCode.ERR_OptionMustBeAbsolutePath; // resources: public override int ERR_CantReadResource => (int)ErrorCode.ERR_CantReadResource; public override int ERR_CantOpenWin32Resource => (int)ErrorCode.ERR_CantOpenWin32Res; public override int ERR_CantOpenWin32Manifest => (int)ErrorCode.ERR_CantOpenWin32Manifest; public override int ERR_CantOpenWin32Icon => (int)ErrorCode.ERR_CantOpenIcon; public override int ERR_ErrorBuildingWin32Resource => (int)ErrorCode.ERR_ErrorBuildingWin32Resources; public override int ERR_BadWin32Resource => (int)ErrorCode.ERR_BadWin32Res; public override int ERR_ResourceFileNameNotUnique => (int)ErrorCode.ERR_ResourceFileNameNotUnique; public override int ERR_ResourceNotUnique => (int)ErrorCode.ERR_ResourceNotUnique; public override int ERR_ResourceInModule => (int)ErrorCode.ERR_CantRefResource; // pseudo-custom attributes: public override int ERR_PermissionSetAttributeFileReadError => (int)ErrorCode.ERR_PermissionSetAttributeFileReadError; // PDB Writer: public override int ERR_EncodinglessSyntaxTree => (int)ErrorCode.ERR_EncodinglessSyntaxTree; public override int WRN_PdbUsingNameTooLong => (int)ErrorCode.WRN_DebugFullNameTooLong; public override int WRN_PdbLocalNameTooLong => (int)ErrorCode.WRN_PdbLocalNameTooLong; public override int ERR_PdbWritingFailed => (int)ErrorCode.FTL_DebugEmitFailure; // PE Writer: public override int ERR_MetadataNameTooLong => (int)ErrorCode.ERR_MetadataNameTooLong; public override int ERR_EncReferenceToAddedMember => (int)ErrorCode.ERR_EncReferenceToAddedMember; public override int ERR_TooManyUserStrings => (int)ErrorCode.ERR_TooManyUserStrings; public override int ERR_PeWritingFailure => (int)ErrorCode.ERR_PeWritingFailure; public override int ERR_ModuleEmitFailure => (int)ErrorCode.ERR_ModuleEmitFailure; public override int ERR_EncUpdateFailedMissingAttribute => (int)ErrorCode.ERR_EncUpdateFailedMissingAttribute; public override int ERR_InvalidDebugInfo => (int)ErrorCode.ERR_InvalidDebugInfo; // Generators: public override int WRN_GeneratorFailedDuringInitialization => (int)ErrorCode.WRN_GeneratorFailedDuringInitialization; public override int WRN_GeneratorFailedDuringGeneration => (int)ErrorCode.WRN_GeneratorFailedDuringGeneration; protected override void ReportInvalidAttributeArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); } protected override void ReportInvalidNamedArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_InvalidNamedArgument, node.ArgumentList.Arguments[namedArgumentIndex].Location, parameterName); } protected override void ReportParameterNotValidForType(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_ParameterNotValidForType, node.ArgumentList.Arguments[namedArgumentIndex].Location); } protected override void ReportMarshalUnmanagedTypeNotValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeNotValidForFields, attributeArgumentSyntax.Location, unmanagedTypeName); } protected override void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, attributeArgumentSyntax.Location, unmanagedTypeName); } protected override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired1, node.Name.Location, parameterName); } protected override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired2, node.Name.Location, parameterName1, parameterName2); } public override int ERR_BadAssemblyName => (int)ErrorCode.ERR_BadAssemblyName; } }
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/TypeVariablesExpansionTests.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.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Evaluation Imports System.Collections.Immutable Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class TypeVariablesExpansionTests Inherits VisualBasicResultProviderTestBase <Fact> Public Sub TypeVariables() Dim source0 = "Class A End Class Class B Inherits A Friend Shared F As Object = 1 End Class" Dim assembly0 = GetAssembly(source0) Dim type0 = assembly0.GetType("B") Dim source1 = ".class private abstract sealed beforefieldinit specialname '<>c__TypeVariables'<T,U> { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } }" Dim assemblyBytes As ImmutableArray(Of Byte) = Nothing Dim pdbBytes As ImmutableArray(Of Byte) = Nothing BasicTestBase.EmitILToArray(source1, appendDefaultHeader:=True, includePdb:=False, assemblyBytes:=assemblyBytes, pdbBytes:=pdbBytes) Dim assembly1 = ReflectionUtilities.Load(assemblyBytes) Dim type1 = assembly1.GetType(ExpressionCompilerConstants.TypeVariablesClassName).MakeGenericType({GetType(Integer), type0}) Dim value = CreateDkmClrValue(value:=Nothing, type:=type1, valueFlags:=DkmClrValueFlags.Synthetic) Dim result = FormatResult("typevars", value) Verify(result, EvalResult("Type variables", "", "", Nothing, DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)) Dim children = GetChildren(result) Verify(children, EvalResult("T", "Integer", "Integer", Nothing, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("U", "B", "B", Nothing, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Evaluation Imports System.Collections.Immutable Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class TypeVariablesExpansionTests Inherits VisualBasicResultProviderTestBase <Fact> Public Sub TypeVariables() Dim source0 = "Class A End Class Class B Inherits A Friend Shared F As Object = 1 End Class" Dim assembly0 = GetAssembly(source0) Dim type0 = assembly0.GetType("B") Dim source1 = ".class private abstract sealed beforefieldinit specialname '<>c__TypeVariables'<T,U> { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } }" Dim assemblyBytes As ImmutableArray(Of Byte) = Nothing Dim pdbBytes As ImmutableArray(Of Byte) = Nothing BasicTestBase.EmitILToArray(source1, appendDefaultHeader:=True, includePdb:=False, assemblyBytes:=assemblyBytes, pdbBytes:=pdbBytes) Dim assembly1 = ReflectionUtilities.Load(assemblyBytes) Dim type1 = assembly1.GetType(ExpressionCompilerConstants.TypeVariablesClassName).MakeGenericType({GetType(Integer), type0}) Dim value = CreateDkmClrValue(value:=Nothing, type:=type1, valueFlags:=DkmClrValueFlags.Synthetic) Dim result = FormatResult("typevars", value) Verify(result, EvalResult("Type variables", "", "", Nothing, DkmEvaluationResultFlags.Expandable Or DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)) Dim children = GetChildren(result) Verify(children, EvalResult("T", "Integer", "Integer", Nothing, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("U", "B", "B", Nothing, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,052
Implement metadata reference provider
Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
chsienki
2021-07-22T19:12:14Z
2021-08-31T16:46:27Z
5e3ecf0550c428d4204c9716f3401c0d54021344
1aeee28e68f0ff099f3bc5944e0a22a02d2b6777
Implement metadata reference provider. Implements a provider for metadata references. Addresses part of https://github.com/dotnet/roslyn/issues/54272 API Review: https://github.com/dotnet/roslyn/issues/55130 closes #55130
./src/EditorFeatures/Core/Extensibility/BraceMatching/IBraceMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Editor { internal interface IBraceMatcher { Task<BraceMatchingResult?> FindBracesAsync(Document document, int position, CancellationToken cancellationToken = default); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Editor { internal interface IBraceMatcher { Task<BraceMatchingResult?> FindBracesAsync(Document document, int position, CancellationToken cancellationToken = default); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a named type symbol whose members are declared in source. /// </summary> internal abstract partial class SourceMemberContainerTypeSymbol : NamedTypeSymbol { // The flags type is used to compact many different bits of information efficiently. private struct Flags { // We current pack everything into one 32-bit int; layout is given below. // // | |vvv|zzzz|f|d|yy|wwwwww| // // w = special type. 6 bits. // y = IsManagedType. 2 bits. // d = FieldDefinitionsNoted. 1 bit // f = FlattenedMembersIsSorted. 1 bit. // z = TypeKind. 4 bits. // v = NullableContext. 3 bits. private int _flags; private const int SpecialTypeOffset = 0; private const int SpecialTypeSize = 6; private const int ManagedKindOffset = SpecialTypeOffset + SpecialTypeSize; private const int ManagedKindSize = 2; private const int FieldDefinitionsNotedOffset = ManagedKindOffset + ManagedKindSize; private const int FieldDefinitionsNotedSize = 1; private const int FlattenedMembersIsSortedOffset = FieldDefinitionsNotedOffset + FieldDefinitionsNotedSize; private const int FlattenedMembersIsSortedSize = 1; private const int TypeKindOffset = FlattenedMembersIsSortedOffset + FlattenedMembersIsSortedSize; private const int TypeKindSize = 4; private const int NullableContextOffset = TypeKindOffset + TypeKindSize; private const int NullableContextSize = 3; private const int SpecialTypeMask = (1 << SpecialTypeSize) - 1; private const int ManagedKindMask = (1 << ManagedKindSize) - 1; private const int TypeKindMask = (1 << TypeKindSize) - 1; private const int NullableContextMask = (1 << NullableContextSize) - 1; private const int FieldDefinitionsNotedBit = 1 << FieldDefinitionsNotedOffset; private const int FlattenedMembersIsSortedBit = 1 << FlattenedMembersIsSortedOffset; public SpecialType SpecialType { get { return (SpecialType)((_flags >> SpecialTypeOffset) & SpecialTypeMask); } } public ManagedKind ManagedKind { get { return (ManagedKind)((_flags >> ManagedKindOffset) & ManagedKindMask); } } public bool FieldDefinitionsNoted { get { return (_flags & FieldDefinitionsNotedBit) != 0; } } // True if "lazyMembersFlattened" is sorted. public bool FlattenedMembersIsSorted { get { return (_flags & FlattenedMembersIsSortedBit) != 0; } } public TypeKind TypeKind { get { return (TypeKind)((_flags >> TypeKindOffset) & TypeKindMask); } } #if DEBUG static Flags() { // Verify masks are sufficient for values. Debug.Assert(EnumUtilities.ContainsAllValues<SpecialType>(SpecialTypeMask)); Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask)); } #endif public Flags(SpecialType specialType, TypeKind typeKind) { int specialTypeInt = ((int)specialType & SpecialTypeMask) << SpecialTypeOffset; int typeKindInt = ((int)typeKind & TypeKindMask) << TypeKindOffset; _flags = specialTypeInt | typeKindInt; } public void SetFieldDefinitionsNoted() { ThreadSafeFlagOperations.Set(ref _flags, FieldDefinitionsNotedBit); } public void SetFlattenedMembersIsSorted() { ThreadSafeFlagOperations.Set(ref _flags, (FlattenedMembersIsSortedBit)); } private static bool BitsAreUnsetOrSame(int bits, int mask) { return (bits & mask) == 0 || (bits & mask) == mask; } public void SetManagedKind(ManagedKind managedKind) { int bitsToSet = ((int)managedKind & ManagedKindMask) << ManagedKindOffset; Debug.Assert(BitsAreUnsetOrSame(_flags, bitsToSet)); ThreadSafeFlagOperations.Set(ref _flags, bitsToSet); } public bool TryGetNullableContext(out byte? value) { return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value); } public bool SetNullableContext(byte? value) { return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset)); } } private static readonly ObjectPool<PooledDictionary<Symbol, Symbol>> s_duplicateRecordMemberSignatureDictionary = PooledDictionary<Symbol, Symbol>.CreatePool(MemberSignatureComparer.RecordAPISignatureComparer); protected SymbolCompletionState state; private Flags _flags; private ImmutableArray<DiagnosticInfo> _managedKindUseSiteDiagnostics; private ImmutableArray<AssemblySymbol> _managedKindUseSiteDependencies; private readonly DeclarationModifiers _declModifiers; private readonly NamespaceOrTypeSymbol _containingSymbol; protected readonly MergedTypeDeclaration declaration; // The entry point symbol (resulting from top-level statements) is needed to construct non-type members because // it contributes to their binders, so we have to compute it first. // The value changes from "uninitialized" to "real value". The transition from "uninitialized" can only happen once. private SimpleProgramEntryPointInfo? _lazySimpleProgramEntryPoint = SimpleProgramEntryPointInfo.UninitializedSentinel; // To compute explicitly declared members, binding must be limited (to avoid race conditions where binder cache captures symbols that aren't part of the final set) // The value changes from "uninitialized" to "real value" to null. The transition from "uninitialized" can only happen once. private DeclaredMembersAndInitializers? _lazyDeclaredMembersAndInitializers = DeclaredMembersAndInitializers.UninitializedSentinel; private MembersAndInitializers? _lazyMembersAndInitializers; private Dictionary<string, ImmutableArray<Symbol>>? _lazyMembersDictionary; private Dictionary<string, ImmutableArray<Symbol>>? _lazyEarlyAttributeDecodingMembersDictionary; private static readonly Dictionary<string, ImmutableArray<NamedTypeSymbol>> s_emptyTypeMembers = new Dictionary<string, ImmutableArray<NamedTypeSymbol>>(EmptyComparer.Instance); private Dictionary<string, ImmutableArray<NamedTypeSymbol>>? _lazyTypeMembers; private ImmutableArray<Symbol> _lazyMembersFlattened; private SynthesizedExplicitImplementations? _lazySynthesizedExplicitImplementations; private int _lazyKnownCircularStruct; private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized; private ThreeState _lazyContainsExtensionMethods; private ThreeState _lazyAnyMemberHasAttributes; #region Construction internal SourceMemberContainerTypeSymbol( NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics, TupleExtraData? tupleData = null) : base(tupleData) { // If we're dealing with a simple program, then we must be in the global namespace Debug.Assert(containingSymbol is NamespaceSymbol { IsGlobalNamespace: true } || !declaration.Declarations.Any(d => d.IsSimpleProgram)); _containingSymbol = containingSymbol; this.declaration = declaration; TypeKind typeKind = declaration.Kind.ToTypeKind(); var modifiers = MakeModifiers(typeKind, diagnostics); foreach (var singleDeclaration in declaration.Declarations) { diagnostics.AddRange(singleDeclaration.Diagnostics); } int access = (int)(modifiers & DeclarationModifiers.AccessibilityMask); if ((access & (access - 1)) != 0) { // more than one access modifier if ((modifiers & DeclarationModifiers.Partial) != 0) diagnostics.Add(ErrorCode.ERR_PartialModifierConflict, Locations[0], this); access = access & ~(access - 1); // narrow down to one access modifier modifiers &= ~DeclarationModifiers.AccessibilityMask; // remove them all modifiers |= (DeclarationModifiers)access; // except the one } _declModifiers = modifiers; var specialType = access == (int)DeclarationModifiers.Public ? MakeSpecialType() : SpecialType.None; _flags = new Flags(specialType, typeKind); var containingType = this.ContainingType; if (containingType?.IsSealed == true && this.DeclaredAccessibility.HasProtected()) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), Locations[0], this); } state.NotePartComplete(CompletionPart.TypeArguments); // type arguments need not be computed separately } private SpecialType MakeSpecialType() { // check if this is one of the COR library types if (ContainingSymbol.Kind == SymbolKind.Namespace && ContainingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes) { //for a namespace, the emitted name is a dot-separated list of containing namespaces var emittedName = ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName); return SpecialTypes.GetTypeFromMetadataName(emittedName); } else { return SpecialType.None; } } private DeclarationModifiers MakeModifiers(TypeKind typeKind, BindingDiagnosticBag diagnostics) { Symbol containingSymbol = this.ContainingSymbol; DeclarationModifiers defaultAccess; var allowedModifiers = DeclarationModifiers.AccessibilityMask; if (containingSymbol.Kind == SymbolKind.Namespace) { defaultAccess = DeclarationModifiers.Internal; } else { allowedModifiers |= DeclarationModifiers.New; if (((NamedTypeSymbol)containingSymbol).IsInterface) { defaultAccess = DeclarationModifiers.Public; } else { defaultAccess = DeclarationModifiers.Private; } } switch (typeKind) { case TypeKind.Class: case TypeKind.Submission: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Unsafe; if (!this.IsRecord) { allowedModifiers |= DeclarationModifiers.Static; } break; case TypeKind.Struct: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Unsafe; if (!this.IsRecordStruct) { allowedModifiers |= DeclarationModifiers.Ref; } break; case TypeKind.Interface: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; break; case TypeKind.Delegate: allowedModifiers |= DeclarationModifiers.Unsafe; break; } bool modifierErrors; var mods = MakeAndCheckTypeModifiers( defaultAccess, allowedModifiers, diagnostics, out modifierErrors); this.CheckUnsafeModifier(mods, diagnostics); if (!modifierErrors && (mods & DeclarationModifiers.Abstract) != 0 && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) != 0) { diagnostics.Add(ErrorCode.ERR_AbstractSealedStatic, Locations[0], this); } if (!modifierErrors && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) { diagnostics.Add(ErrorCode.ERR_SealedStaticClass, Locations[0], this); } switch (typeKind) { case TypeKind.Interface: mods |= DeclarationModifiers.Abstract; break; case TypeKind.Struct: case TypeKind.Enum: mods |= DeclarationModifiers.Sealed; break; case TypeKind.Delegate: mods |= DeclarationModifiers.Sealed; break; } return mods; } private DeclarationModifiers MakeAndCheckTypeModifiers( DeclarationModifiers defaultAccess, DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics, out bool modifierErrors) { modifierErrors = false; var result = DeclarationModifiers.Unset; var partCount = declaration.Declarations.Length; var missingPartial = false; for (var i = 0; i < partCount; i++) { var decl = declaration.Declarations[i]; var mods = decl.Modifiers; if (partCount > 1 && (mods & DeclarationModifiers.Partial) == 0) { missingPartial = true; } if (!modifierErrors) { mods = ModifierUtils.CheckModifiers( mods, allowedModifiers, declaration.Declarations[i].NameLocation, diagnostics, modifierTokens: null, modifierErrors: out modifierErrors); // It is an error for the same modifier to appear multiple times. if (!modifierErrors) { var info = ModifierUtils.CheckAccessibility(mods, this, isExplicitInterfaceImplementation: false); if (info != null) { diagnostics.Add(info, this.Locations[0]); modifierErrors = true; } } } if (result == DeclarationModifiers.Unset) { result = mods; } else { result |= mods; } } if ((result & DeclarationModifiers.AccessibilityMask) == 0) { result |= defaultAccess; } if (missingPartial) { if ((result & DeclarationModifiers.Partial) == 0) { // duplicate definitions switch (this.ContainingSymbol.Kind) { case SymbolKind.Namespace: for (var i = 1; i < partCount; i++) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, declaration.Declarations[i].NameLocation, this.Name, this.ContainingSymbol); modifierErrors = true; } break; case SymbolKind.NamedType: for (var i = 1; i < partCount; i++) { if (ContainingType!.Locations.Length == 1 || ContainingType.IsPartial()) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, declaration.Declarations[i].NameLocation, this.ContainingSymbol, this.Name); modifierErrors = true; } break; } } else { for (var i = 0; i < partCount; i++) { var singleDeclaration = declaration.Declarations[i]; var mods = singleDeclaration.Modifiers; if ((mods & DeclarationModifiers.Partial) == 0) { diagnostics.Add(ErrorCode.ERR_MissingPartial, singleDeclaration.NameLocation, this.Name); modifierErrors = true; } } } } if (this.Name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword)) { foreach (var syntaxRef in SyntaxReferences) { SyntaxToken? identifier = syntaxRef.GetSyntax() switch { BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier, DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier, _ => null }; ReportTypeNamedRecord(identifier?.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, identifier?.GetLocation() ?? Location.None); } } return result; } internal static void ReportTypeNamedRecord(string? name, CSharpCompilation compilation, DiagnosticBag? diagnostics, Location location) { if (diagnostics is object && name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword) && compilation.LanguageVersion >= MessageID.IDS_FeatureRecords.RequiredVersion()) { diagnostics.Add(ErrorCode.WRN_RecordNamedDisallowed, location, name); } } #endregion #region Completion internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } protected abstract void CheckBase(BindingDiagnosticBag diagnostics); protected abstract void CheckInterfaces(BindingDiagnosticBag diagnostics); internal override void ForceComplete(SourceLocation? locationOpt, CancellationToken cancellationToken) { while (true) { // NOTE: cases that depend on GetMembers[ByName] should call RequireCompletionPartMembers. cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.StartBaseType: case CompletionPart.FinishBaseType: if (state.NotePartComplete(CompletionPart.StartBaseType)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckBase(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishBaseType); diagnostics.Free(); } break; case CompletionPart.StartInterfaces: case CompletionPart.FinishInterfaces: if (state.NotePartComplete(CompletionPart.StartInterfaces)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckInterfaces(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishInterfaces); diagnostics.Free(); } break; case CompletionPart.EnumUnderlyingType: var discarded = this.EnumUnderlyingType; break; case CompletionPart.TypeArguments: { var tmp = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; // force type arguments } break; case CompletionPart.TypeParameters: // force type parameters foreach (var typeParameter in this.TypeParameters) { typeParameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.TypeParameters); break; case CompletionPart.Members: this.GetMembersByName(); break; case CompletionPart.TypeMembers: this.GetTypeMembersUnordered(); break; case CompletionPart.SynthesizedExplicitImplementations: this.GetSynthesizedExplicitImplementations(cancellationToken); //force interface and base class errors to be checked break; case CompletionPart.StartMemberChecks: case CompletionPart.FinishMemberChecks: if (state.NotePartComplete(CompletionPart.StartMemberChecks)) { var diagnostics = BindingDiagnosticBag.GetInstance(); AfterMembersChecks(diagnostics); AddDeclarationDiagnostics(diagnostics); // We may produce a SymbolDeclaredEvent for the enclosing type before events for its contained members DeclaringCompilation.SymbolDeclaredEvent(this); var thisThreadCompleted = state.NotePartComplete(CompletionPart.FinishMemberChecks); Debug.Assert(thisThreadCompleted); diagnostics.Free(); } break; case CompletionPart.MembersCompleted: { ImmutableArray<Symbol> members = this.GetMembersUnordered(); bool allCompleted = true; if (locationOpt == null) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); member.ForceComplete(locationOpt, cancellationToken); } } else { foreach (var member in members) { ForceCompleteMemberByLocation(locationOpt, member, cancellationToken); allCompleted = allCompleted && member.HasComplete(CompletionPart.All); } } if (!allCompleted) { // We did not complete all members so we won't have enough information for // the PointedAtManagedTypeChecks, so just kick out now. var allParts = CompletionPart.NamedTypeSymbolWithLocationAll; state.SpinWaitComplete(allParts, cancellationToken); return; } EnsureFieldDefinitionsNoted(); // We've completed all members, so we're ready for the PointedAtManagedTypeChecks; // proceed to the next iteration. state.NotePartComplete(CompletionPart.MembersCompleted); break; } case CompletionPart.None: return; default: // This assert will trigger if we forgot to handle any of the completion parts Debug.Assert((incompletePart & CompletionPart.NamedTypeSymbolAll) == 0); // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.NamedTypeSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } throw ExceptionUtilities.Unreachable; } internal void EnsureFieldDefinitionsNoted() { if (_flags.FieldDefinitionsNoted) { return; } NoteFieldDefinitions(); } private void NoteFieldDefinitions() { // we must note all fields once therefore we need to lock var membersAndInitializers = this.GetMembersAndInitializers(); lock (membersAndInitializers) { if (!_flags.FieldDefinitionsNoted) { var assembly = (SourceAssemblySymbol)ContainingAssembly; Accessibility containerEffectiveAccessibility = EffectiveAccessibility(); foreach (var member in membersAndInitializers.NonTypeMembers) { FieldSymbol field; if (!member.IsFieldOrFieldLikeEvent(out field) || field.IsConst || field.IsFixedSizeBuffer) { continue; } Accessibility fieldDeclaredAccessibility = field.DeclaredAccessibility; if (fieldDeclaredAccessibility == Accessibility.Private) { // mark private fields as tentatively unassigned and unread unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: true); } else if (containerEffectiveAccessibility == Accessibility.Private) { // mark effectively private fields as tentatively unassigned unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: false); } else if (fieldDeclaredAccessibility == Accessibility.Internal || containerEffectiveAccessibility == Accessibility.Internal) { // mark effectively internal fields as tentatively unassigned unless we discover otherwise. // NOTE: These fields will be reported as unassigned only if internals are not visible from this assembly. // See property SourceAssemblySymbol.UnusedFieldWarnings. assembly.NoteFieldDefinition(field, isInternal: true, isUnread: false); } } _flags.SetFieldDefinitionsNoted(); } } } #endregion #region Containers public sealed override NamedTypeSymbol? ContainingType { get { return _containingSymbol as NamedTypeSymbol; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } #endregion #region Flags Encoded Properties public override SpecialType SpecialType { get { return _flags.SpecialType; } } public override TypeKind TypeKind { get { return _flags.TypeKind; } } internal MergedTypeDeclaration MergedDeclaration { get { return this.declaration; } } internal sealed override bool IsInterface { get { // TypeKind is computed eagerly, so this is cheap. return this.TypeKind == TypeKind.Interface; } } internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var managedKind = _flags.ManagedKind; if (managedKind == ManagedKind.Unknown) { var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(ContainingAssembly); managedKind = base.GetManagedKind(ref managedKindUseSiteInfo); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDiagnostics, managedKindUseSiteInfo.Diagnostics?.ToImmutableArray() ?? ImmutableArray<DiagnosticInfo>.Empty); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDependencies, managedKindUseSiteInfo.Dependencies?.ToImmutableArray() ?? ImmutableArray<AssemblySymbol>.Empty); _flags.SetManagedKind(managedKind); } if (useSiteInfo.AccumulatesDiagnostics) { ImmutableArray<DiagnosticInfo> useSiteDiagnostics = _managedKindUseSiteDiagnostics; // Ensure we have the latest value from the field useSiteDiagnostics = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDiagnostics, useSiteDiagnostics, useSiteDiagnostics); Debug.Assert(!useSiteDiagnostics.IsDefault); useSiteInfo.AddDiagnostics(useSiteDiagnostics); } if (useSiteInfo.AccumulatesDependencies) { ImmutableArray<AssemblySymbol> useSiteDependencies = _managedKindUseSiteDependencies; // Ensure we have the latest value from the field useSiteDependencies = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDependencies, useSiteDependencies, useSiteDependencies); Debug.Assert(!useSiteDependencies.IsDefault); useSiteInfo.AddDependencies(useSiteDependencies); } return managedKind; } public override bool IsStatic => HasFlag(DeclarationModifiers.Static); public sealed override bool IsRefLikeType => HasFlag(DeclarationModifiers.Ref); public override bool IsReadOnly => HasFlag(DeclarationModifiers.ReadOnly); public override bool IsSealed => HasFlag(DeclarationModifiers.Sealed); public override bool IsAbstract => HasFlag(DeclarationModifiers.Abstract); internal bool IsPartial => HasFlag(DeclarationModifiers.Partial); internal bool IsNew => HasFlag(DeclarationModifiers.New); [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HasFlag(DeclarationModifiers flag) => (_declModifiers & flag) != 0; public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(_declModifiers); } } /// <summary> /// Compute the "effective accessibility" of the current class for the purpose of warnings about unused fields. /// </summary> private Accessibility EffectiveAccessibility() { var result = DeclaredAccessibility; if (result == Accessibility.Private) return Accessibility.Private; for (Symbol? container = this.ContainingType; !(container is null); container = container.ContainingType) { switch (container.DeclaredAccessibility) { case Accessibility.Private: return Accessibility.Private; case Accessibility.Internal: result = Accessibility.Internal; continue; } } return result; } #endregion #region Syntax public override bool IsScriptClass { get { var kind = this.declaration.Declarations[0].Kind; return kind == DeclarationKind.Script || kind == DeclarationKind.Submission; } } public override bool IsImplicitClass { get { return this.declaration.Declarations[0].Kind == DeclarationKind.ImplicitClass; } } internal override bool IsRecord { get { return this.declaration.Declarations[0].Kind == DeclarationKind.Record; } } internal override bool IsRecordStruct { get { return this.declaration.Declarations[0].Kind == DeclarationKind.RecordStruct; } } public override bool IsImplicitlyDeclared { get { return IsImplicitClass || IsScriptClass; } } public override int Arity { get { return declaration.Arity; } } public override string Name { get { return declaration.Name; } } internal override bool MangleName { get { return Arity > 0; } } internal override LexicalSortKey GetLexicalSortKey() { if (!_lazyLexicalSortKey.IsInitialized) { _lazyLexicalSortKey.SetFrom(declaration.GetLexicalSortKey(this.DeclaringCompilation)); } return _lazyLexicalSortKey; } public override ImmutableArray<Location> Locations { get { return declaration.NameLocations.Cast<SourceLocation, Location>(); } } public ImmutableArray<SyntaxReference> SyntaxReferences { get { return this.declaration.SyntaxReferences; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return SyntaxReferences; } } // This method behaves the same was as the base class, but avoids allocations associated with DeclaringSyntaxReferences internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken) { var declarations = declaration.Declarations; if (IsImplicitlyDeclared && declarations.IsEmpty) { return ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken); } foreach (var declaration in declarations) { cancellationToken.ThrowIfCancellationRequested(); var syntaxRef = declaration.SyntaxReference; if (syntaxRef.SyntaxTree == tree && (!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value))) { return true; } } return false; } #endregion #region Members /// <summary> /// Encapsulates information about the non-type members of a (i.e. this) type. /// 1) For non-initializers, symbols are created and stored in a list. /// 2) For fields and properties/indexers, the symbols are stored in (1) and their initializers are /// stored with other initialized fields and properties from the same syntax tree with /// the same static-ness. /// </summary> protected sealed class MembersAndInitializers { internal readonly ImmutableArray<Symbol> NonTypeMembers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; internal readonly bool HaveIndexers; internal readonly bool IsNullableEnabledForInstanceConstructorsAndFields; internal readonly bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields) { Debug.Assert(!nonTypeMembers.IsDefault); Debug.Assert(!staticInitializers.IsDefault); Debug.Assert(staticInitializers.All(g => !g.IsDefault)); Debug.Assert(!instanceInitializers.IsDefault); Debug.Assert(instanceInitializers.All(g => !g.IsDefault)); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(haveIndexers == nonTypeMembers.Any(s => s.IsIndexer())); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers { get { return GetMembersAndInitializers().StaticInitializers; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers { get { return GetMembersAndInitializers().InstanceInitializers; } } internal int CalculateSyntaxOffsetInSynthesizedConstructor(int position, SyntaxTree tree, bool isStatic) { if (IsScriptClass && !isStatic) { int aggregateLength = 0; foreach (var declaration in this.declaration.Declarations) { var syntaxRef = declaration.SyntaxReference; if (tree == syntaxRef.SyntaxTree) { return aggregateLength + position; } aggregateLength += syntaxRef.Span.Length; } throw ExceptionUtilities.Unreachable; } int syntaxOffset; if (TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, isStatic, ctorInitializerLength: 0, syntaxOffset: out syntaxOffset)) { return syntaxOffset; } if (declaration.Declarations.Length >= 1 && position == declaration.Declarations[0].Location.SourceSpan.Start) { // With dynamic analysis instrumentation, the introducing declaration of a type can provide // the syntax associated with both the analysis payload local of a synthesized constructor // and with the constructor itself. If the synthesized constructor includes an initializer with a lambda, // that lambda needs a closure that captures the analysis payload of the constructor, // and the offset of the syntax for the local within the constructor is by definition zero. return 0; } // an implicit constructor has no body and no initializer, so the variable has to be declared in a member initializer throw ExceptionUtilities.Unreachable; } /// <summary> /// Calculates a syntax offset of a syntax position that is contained in a property or field initializer (if it is in fact contained in one). /// </summary> internal bool TryCalculateSyntaxOffsetOfPositionInInitializer(int position, SyntaxTree tree, bool isStatic, int ctorInitializerLength, out int syntaxOffset) { Debug.Assert(ctorInitializerLength >= 0); var membersAndInitializers = GetMembersAndInitializers(); var allInitializers = isStatic ? membersAndInitializers.StaticInitializers : membersAndInitializers.InstanceInitializers; if (!findInitializer(allInitializers, position, tree, out FieldOrPropertyInitializer initializer, out int precedingLength)) { syntaxOffset = 0; return false; } // |<-----------distanceFromCtorBody----------->| // [ initializer 0 ][ initializer 1 ][ initializer 2 ][ctor initializer][ctor body] // |<--preceding init len-->| ^ // position int initializersLength = getInitializersLength(allInitializers); int distanceFromInitializerStart = position - initializer.Syntax.Span.Start; int distanceFromCtorBody = initializersLength + ctorInitializerLength - (precedingLength + distanceFromInitializerStart); Debug.Assert(distanceFromCtorBody > 0); // syntax offset 0 is at the start of the ctor body: syntaxOffset = -distanceFromCtorBody; return true; static bool findInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, int position, SyntaxTree tree, out FieldOrPropertyInitializer found, out int precedingLength) { precedingLength = 0; foreach (var group in initializers) { if (!group.IsEmpty && group[0].Syntax.SyntaxTree == tree && position < group.Last().Syntax.Span.End) { // Found group of interest var initializerIndex = IndexOfInitializerContainingPosition(group, position); if (initializerIndex < 0) { break; } precedingLength += getPrecedingInitializersLength(group, initializerIndex); found = group[initializerIndex]; return true; } precedingLength += getGroupLength(group); } found = default; return false; } static int getGroupLength(ImmutableArray<FieldOrPropertyInitializer> initializers) { int length = 0; foreach (var initializer in initializers) { length += getInitializerLength(initializer); } return length; } static int getPrecedingInitializersLength(ImmutableArray<FieldOrPropertyInitializer> initializers, int index) { int length = 0; for (var i = 0; i < index; i++) { length += getInitializerLength(initializers[i]); } return length; } static int getInitializersLength(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { int length = 0; foreach (var group in initializers) { length += getGroupLength(group); } return length; } static int getInitializerLength(FieldOrPropertyInitializer initializer) { // A constant field of type decimal needs a field initializer, so // check if it is a metadata constant, not just a constant to exclude // decimals. Other constants do not need field initializers. if (initializer.FieldOpt == null || !initializer.FieldOpt.IsMetadataConstant) { // ignore leading and trailing trivia of the node: return initializer.Syntax.Span.Length; } return 0; } } private static int IndexOfInitializerContainingPosition(ImmutableArray<FieldOrPropertyInitializer> initializers, int position) { // Search for the start of the span (the spans are non-overlapping and sorted) int index = initializers.BinarySearch(position, (initializer, pos) => initializer.Syntax.Span.Start.CompareTo(pos)); // Binary search returns non-negative result if the position is exactly the start of some span. if (index >= 0) { return index; } // Otherwise, ~index is the closest span whose start is greater than the position. // => Check if the preceding initializer span contains the position. int precedingInitializerIndex = ~index - 1; if (precedingInitializerIndex >= 0 && initializers[precedingInitializerIndex].Syntax.Span.Contains(position)) { return precedingInitializerIndex; } return -1; } public override IEnumerable<string> MemberNames { get { return (IsTupleType || IsRecord || IsRecordStruct) ? GetMembers().Select(m => m.Name) : this.declaration.MemberNames; } } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return GetTypeMembersDictionary().Flatten(); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return GetTypeMembersDictionary().Flatten(LexicalOrderSymbolComparer.Instance); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { ImmutableArray<NamedTypeSymbol> members; if (GetTypeMembersDictionary().TryGetValue(name, out members)) { return members; } return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity); } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetTypeMembersDictionary() { if (_lazyTypeMembers == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); if (Interlocked.CompareExchange(ref _lazyTypeMembers, MakeTypeMembers(diagnostics), null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.TypeMembers); } diagnostics.Free(); } return _lazyTypeMembers; } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> MakeTypeMembers(BindingDiagnosticBag diagnostics) { var symbols = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var conflictDict = new Dictionary<(string, int), SourceNamedTypeSymbol>(); try { foreach (var childDeclaration in declaration.Children) { var t = new SourceNamedTypeSymbol(this, childDeclaration, diagnostics); this.CheckMemberNameDistinctFromType(t, diagnostics); var key = (t.Name, t.Arity); SourceNamedTypeSymbol? other; if (conflictDict.TryGetValue(key, out other)) { if (Locations.Length == 1 || IsPartial) { if (t.IsPartial && other.IsPartial) { diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, t.Locations[0], t); } else { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, t.Locations[0], this, t.Name); } } } else { conflictDict.Add(key, t); } symbols.Add(t); } if (IsInterface) { foreach (var t in symbols) { Binder.CheckFeatureAvailability(t.DeclaringSyntaxReferences[0].GetSyntax(), MessageID.IDS_DefaultInterfaceImplementation, diagnostics, t.Locations[0]); } } Debug.Assert(s_emptyTypeMembers.Count == 0); return symbols.Count > 0 ? symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance) : s_emptyTypeMembers; } finally { symbols.Free(); } } private void CheckMemberNameDistinctFromType(Symbol member, BindingDiagnosticBag diagnostics) { switch (this.TypeKind) { case TypeKind.Class: case TypeKind.Struct: if (member.Name == this.Name) { diagnostics.Add(ErrorCode.ERR_MemberNameSameAsType, member.Locations[0], this.Name); } break; case TypeKind.Interface: if (member.IsStatic) { goto case TypeKind.Class; } break; } } internal override ImmutableArray<Symbol> GetMembersUnordered() { var result = _lazyMembersFlattened; if (result.IsDefault) { result = GetMembersByName().Flatten(null); // do not sort. ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersFlattened, result); result = _lazyMembersFlattened; } return result.ConditionallyDeOrder(); } public override ImmutableArray<Symbol> GetMembers() { if (_flags.FlattenedMembersIsSorted) { return _lazyMembersFlattened; } else { var allMembers = this.GetMembersUnordered(); if (allMembers.Length > 1) { // The array isn't sorted. Sort it and remember that we sorted it. allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance); ImmutableInterlocked.InterlockedExchange(ref _lazyMembersFlattened, allMembers); } _flags.SetFlattenedMembersIsSorted(); return allMembers; } } public sealed override ImmutableArray<Symbol> GetMembers(string name) { ImmutableArray<Symbol> members; if (GetMembersByName().TryGetValue(name, out members)) { return members; } return ImmutableArray<Symbol>.Empty; } /// <remarks> /// For source symbols, there can only be a valid clone method if this is a record, which is a /// simple syntax check. This will need to change when we generalize cloning, but it's a good /// heuristic for now. /// </remarks> internal override bool HasPossibleWellKnownCloneMethod() => IsRecord; internal override ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { if (_lazyMembersDictionary != null || declaration.MemberNames.Contains(name) || declaration.Kind is DeclarationKind.Record or DeclarationKind.RecordStruct) { return GetMembers(name); } return ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { if (this.TypeKind == TypeKind.Enum) { // For consistency with Dev10, emit value__ field first. var valueField = ((SourceNamedTypeSymbol)this).EnumValueField; RoslynDebug.Assert((object)valueField != null); yield return valueField; } foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: if (m is TupleErrorFieldSymbol) { break; } yield return (FieldSymbol)m; break; case SymbolKind.Event: FieldSymbol? associatedField = ((EventSymbol)m).AssociatedField; if ((object?)associatedField != null) { yield return associatedField; } break; } } } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return GetEarlyAttributeDecodingMembersDictionary().Flatten(); } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol that have a particular name. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { ImmutableArray<Symbol> result; return GetEarlyAttributeDecodingMembersDictionary().TryGetValue(name, out result) ? result : ImmutableArray<Symbol>.Empty; } private Dictionary<string, ImmutableArray<Symbol>> GetEarlyAttributeDecodingMembersDictionary() { if (_lazyEarlyAttributeDecodingMembersDictionary == null) { if (Volatile.Read(ref _lazyMembersDictionary) is Dictionary<string, ImmutableArray<Symbol>> result) { return result; } var membersAndInitializers = GetMembersAndInitializers(); //NOTE: separately cached // NOTE: members were added in a single pass over the syntax, so they're already // in lexical order. Dictionary<string, ImmutableArray<Symbol>> membersByName; if (!membersAndInitializers.HaveIndexers) { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name); } else { // We can't include indexer symbol yet, because we don't know // what name it will have after attribute binding (because of // IndexerNameAttribute). membersByName = membersAndInitializers.NonTypeMembers. WhereAsArray(s => !s.IsIndexer() && (!s.IsAccessor() || ((MethodSymbol)s).AssociatedSymbol?.IsIndexer() != true)). ToDictionary(s => s.Name); } AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); Interlocked.CompareExchange(ref _lazyEarlyAttributeDecodingMembersDictionary, membersByName, null); } return _lazyEarlyAttributeDecodingMembersDictionary; } // NOTE: this method should do as little work as possible // we often need to get members just to do a lookup. // All additional checks and diagnostics may be not // needed yet or at all. protected MembersAndInitializers GetMembersAndInitializers() { var membersAndInitializers = _lazyMembersAndInitializers; if (membersAndInitializers != null) { return membersAndInitializers; } var diagnostics = BindingDiagnosticBag.GetInstance(); membersAndInitializers = BuildMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyMembersAndInitializers, membersAndInitializers, null); if (alreadyKnown != null) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); _lazyDeclaredMembersAndInitializers = null; return membersAndInitializers!; } /// <summary> /// The purpose of this function is to assert that the <paramref name="member"/> symbol /// is actually among the symbols cached by this type symbol in a way that ensures /// that any consumer of standard APIs to get to type's members is going to get the same /// symbol (same instance) for the member rather than an equivalent, but different instance. /// </summary> [Conditional("DEBUG")] internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false) { if (member is FieldSymbol && forDiagnostics && this.IsTupleType) { // There is a problem with binding types of fields in tuple types. // Skipping verification for them temporarily. return; } if (member is NamedTypeSymbol type) { RoslynDebug.AssertOrFailFast(forDiagnostics); RoslynDebug.AssertOrFailFast(Volatile.Read(ref _lazyTypeMembers)?.Values.Any(types => types.Contains(t => t == (object)type)) == true); return; } else if (member is TypeParameterSymbol || member is SynthesizedMethodBaseSymbol) { RoslynDebug.AssertOrFailFast(forDiagnostics); return; } else if (member is FieldSymbol field && field.AssociatedSymbol is EventSymbol e) { RoslynDebug.AssertOrFailFast(forDiagnostics); // Backing fields for field-like events are not added to the members list. member = e; } var membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } if (membersAndInitializers is null) { if (member is SynthesizedSimpleProgramEntryPointSymbol) { RoslynDebug.AssertOrFailFast(GetSimpleProgramEntryPoints().Contains(m => m == (object)member)); return; } var declared = Volatile.Read(ref _lazyDeclaredMembersAndInitializers); RoslynDebug.AssertOrFailFast(declared != DeclaredMembersAndInitializers.UninitializedSentinel); if (declared is object) { if (declared.NonTypeMembers.Contains(m => m == (object)member) || declared.RecordPrimaryConstructor == (object)member) { return; } } else { // It looks like there was a race and we need to check _lazyMembersAndInitializers again membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); RoslynDebug.AssertOrFailFast(membersAndInitializers is object); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } } } RoslynDebug.AssertOrFailFast(false, "Premature symbol exposure."); static bool isMemberInCompleteMemberList(MembersAndInitializers? membersAndInitializers, Symbol member) { return membersAndInitializers?.NonTypeMembers.Contains(m => m == (object)member) == true; } } protected Dictionary<string, ImmutableArray<Symbol>> GetMembersByName() { if (this.state.HasComplete(CompletionPart.Members)) { return _lazyMembersDictionary!; } return GetMembersByNameSlow(); } private Dictionary<string, ImmutableArray<Symbol>> GetMembersByNameSlow() { if (_lazyMembersDictionary == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); var membersDictionary = MakeAllMembers(diagnostics); if (Interlocked.CompareExchange(ref _lazyMembersDictionary, membersDictionary, null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.Members); } diagnostics.Free(); } state.SpinWaitComplete(CompletionPart.Members, default(CancellationToken)); return _lazyMembersDictionary; } internal override IEnumerable<Symbol> GetInstanceFieldsAndEvents() { var membersAndInitializers = this.GetMembersAndInitializers(); return membersAndInitializers.NonTypeMembers.Where(IsInstanceFieldOrEvent); } protected void AfterMembersChecks(BindingDiagnosticBag diagnostics) { if (IsInterface) { CheckInterfaceMembers(this.GetMembersAndInitializers().NonTypeMembers, diagnostics); } CheckMemberNamesDistinctFromType(diagnostics); CheckMemberNameConflicts(diagnostics); CheckRecordMemberNames(diagnostics); CheckSpecialMemberErrors(diagnostics); CheckTypeParameterNameConflicts(diagnostics); CheckAccessorNameConflicts(diagnostics); bool unused = KnownCircularStruct; CheckSequentialOnPartialType(diagnostics); CheckForProtectedInStaticClass(diagnostics); CheckForUnmatchedOperators(diagnostics); var location = Locations[0]; var compilation = DeclaringCompilation; if (this.IsRefLikeType) { compilation.EnsureIsByRefLikeAttributeExists(diagnostics, location, modifyCompilation: true); } if (this.IsReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } var baseType = BaseTypeNoUseSiteDiagnostics; var interfaces = GetInterfacesToEmit(); // https://github.com/dotnet/roslyn/issues/30080: Report diagnostics for base type and interfaces at more specific locations. if (hasBaseTypeOrInterface(t => t.ContainsNativeInteger())) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true); } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out _)) { compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true); } if (hasBaseTypeOrInterface(t => t.NeedsNullableAttribute())) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true); } } if (interfaces.Any(t => needsTupleElementNamesAttribute(t))) { // Note: we don't need to check base type or directly implemented interfaces (which will be reported during binding) // so the checking of all interfaces here involves some redundancy. Binder.ReportMissingTupleElementNamesAttributesIfNeeded(compilation, location, diagnostics); } bool hasBaseTypeOrInterface(Func<NamedTypeSymbol, bool> predicate) { return ((object)baseType != null && predicate(baseType)) || interfaces.Any(predicate); } static bool needsTupleElementNamesAttribute(TypeSymbol type) { if (type is null) { return false; } var resultType = type.VisitType( predicate: (t, a, b) => !t.TupleElementNames.IsDefaultOrEmpty && !t.IsErrorType(), arg: (object?)null); return resultType is object; } } private void CheckMemberNamesDistinctFromType(BindingDiagnosticBag diagnostics) { foreach (var member in GetMembersAndInitializers().NonTypeMembers) { CheckMemberNameDistinctFromType(member, diagnostics); } } private void CheckRecordMemberNames(BindingDiagnosticBag diagnostics) { if (declaration.Kind != DeclarationKind.Record && declaration.Kind != DeclarationKind.RecordStruct) { return; } foreach (var member in GetMembers("Clone")) { diagnostics.Add(ErrorCode.ERR_CloneDisallowedInRecord, member.Locations[0]); } } private void CheckMemberNameConflicts(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName = GetMembersByName(); // Collisions involving indexers are handled specially. CheckIndexerNameConflicts(diagnostics, membersByName); // key and value will be the same object in these dictionaries. var methodsBySignature = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsMethods = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsConversions = new HashSet<SourceUserDefinedConversionSymbol>(ConversionSignatureComparer.Comparer); // SPEC: The signature of an operator must differ from the signatures of all other // SPEC: operators declared in the same class. // DELIBERATE SPEC VIOLATION: // The specification does not state that a user-defined conversion reserves the names // op_Implicit or op_Explicit, but nevertheless the native compiler does so; an attempt // to define a field or a conflicting method with the metadata name of a user-defined // conversion is an error. We preserve this reasonable behavior. // // Similarly, we treat "public static C operator +(C, C)" as colliding with // "public static C op_Addition(C, C)". Fortunately, this behavior simply // falls out of treating user-defined operators as ordinary methods; we do // not need any special handling in this method. // // However, we must have special handling for conversions because conversions // use a completely different rule for detecting collisions between two // conversions: conversion signatures consist only of the source and target // types of the conversions, and not the kind of the conversion (implicit or explicit), // the name of the method, and so on. // // Therefore we must detect the following kinds of member name conflicts: // // 1. a method, conversion or field has the same name as a (different) field (* see note below) // 2. a method has the same method signature as another method or conversion // 3. a conversion has the same conversion signature as another conversion. // // However, we must *not* detect "a conversion has the same *method* signature // as another conversion" because conversions are allowed to overload on // return type but methods are not. // // (*) NOTE: Throughout the rest of this method I will use "field" as a shorthand for // "non-method, non-conversion, non-type member", rather than spelling out // "field, property or event...") foreach (var pair in membersByName) { var name = pair.Key; Symbol? lastSym = GetTypeMembers(name).FirstOrDefault(); methodsBySignature.Clear(); // Conversion collisions do not consider the name of the conversion, // so do not clear that dictionary. foreach (var symbol in pair.Value) { if (symbol.Kind == SymbolKind.NamedType || symbol.IsAccessor() || symbol.IsIndexer()) { continue; } // We detect the first category of conflict by running down the list of members // of the same name, and producing an error when we discover any of the following // "bad transitions". // // * a method or conversion that comes after any field (not necessarily directly) // * a field directly following a field // * a field directly following a method or conversion // // Furthermore: we do not wish to detect collisions between nested types in // this code; that is tested elsewhere. However, we do wish to detect a collision // between a nested type and a field, method or conversion. Therefore we // initialize our "bad transition" detector with a type of the given name, // if there is one. That way we also detect the transitions of "method following // type", and so on. // // The "lastSym" local below is used to detect these transitions. Its value is // one of the following: // // * a nested type of the given name, or // * the first method of the given name, or // * the most recently processed field of the given name. // // If either the current symbol or the "last symbol" are not methods then // there must be a collision: // // * if the current symbol is not a method and the last symbol is, then // there is a field directly following a method of the same name // * if the current symbol is a method and the last symbol is not, then // there is a method directly or indirectly following a field of the same name, // or a method of the same name as a nested type. // * if neither are methods then either we have a field directly // following a field of the same name, or a field and a nested type of the same name. // if (lastSym is object) { if (symbol.Kind != SymbolKind.Method || lastSym.Kind != SymbolKind.Method) { if (symbol.Kind != SymbolKind.Field || !symbol.IsImplicitlyDeclared) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, symbol.Locations[0], this, symbol.Name); } } if (lastSym.Kind == SymbolKind.Method) { lastSym = symbol; } } } else { lastSym = symbol; } // That takes care of the first category of conflict; we detect the // second and third categories as follows: var conversion = symbol as SourceUserDefinedConversionSymbol; var method = symbol as SourceMemberMethodSymbol; if (!(conversion is null)) { // Does this conversion collide *as a conversion* with any previously-seen // conversion? if (!conversionsAsConversions.Add(conversion)) { // CS0557: Duplicate user-defined conversion in type 'C' diagnostics.Add(ErrorCode.ERR_DuplicateConversionInClass, conversion.Locations[0], this); } else { // The other set might already contain a conversion which would collide // *as a method* with the current conversion. if (!conversionsAsMethods.ContainsKey(conversion)) { conversionsAsMethods.Add(conversion, conversion); } } // Does this conversion collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(conversion, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, conversion, previousMethod); } // Do not add the conversion to the set of previously-seen methods; that set // is only non-conversion methods. } else if (!(method is null)) { // Does this method collide *as a method* with any previously-seen // conversion? if (conversionsAsMethods.TryGetValue(method, out var previousConversion)) { ReportMethodSignatureCollision(diagnostics, method, previousConversion); } // Do not add the method to the set of previously-seen conversions. // Does this method collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(method, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, method, previousMethod); } else { // We haven't seen this method before. Make a note of it in case // we see a colliding method later. methodsBySignature.Add(method, method); } } } } } // Report a name conflict; the error is reported on the location of method1. // UNDONE: Consider adding a secondary location pointing to the second method. private void ReportMethodSignatureCollision(BindingDiagnosticBag diagnostics, SourceMemberMethodSymbol method1, SourceMemberMethodSymbol method2) { switch (method1, method2) { case (SourceOrdinaryMethodSymbol { IsPartialDefinition: true }, SourceOrdinaryMethodSymbol { IsPartialImplementation: true }): case (SourceOrdinaryMethodSymbol { IsPartialImplementation: true }, SourceOrdinaryMethodSymbol { IsPartialDefinition: true }): // these could be 2 parts of the same partial method. // Partial methods are allowed to collide by signature. return; case (SynthesizedSimpleProgramEntryPointSymbol { }, SynthesizedSimpleProgramEntryPointSymbol { }): return; } // If method1 is a constructor only because its return type is missing, then // we've already produced a diagnostic for the missing return type and we suppress the // diagnostic about duplicate signature. if (method1.MethodKind == MethodKind.Constructor && ((ConstructorDeclarationSyntax)method1.SyntaxRef.GetSyntax()).Identifier.ValueText != this.Name) { return; } Debug.Assert(method1.ParameterCount == method2.ParameterCount); for (int i = 0; i < method1.ParameterCount; i++) { var refKind1 = method1.Parameters[i].RefKind; var refKind2 = method2.Parameters[i].RefKind; if (refKind1 != refKind2) { // '{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}' var methodKind = method1.MethodKind == MethodKind.Constructor ? MessageID.IDS_SK_CONSTRUCTOR : MessageID.IDS_SK_METHOD; diagnostics.Add(ErrorCode.ERR_OverloadRefKind, method1.Locations[0], this, methodKind.Localize(), refKind1.ToParameterDisplayString(), refKind2.ToParameterDisplayString()); return; } } // Special case: if there are two destructors, use the destructor syntax instead of "Finalize" var methodName = (method1.MethodKind == MethodKind.Destructor && method2.MethodKind == MethodKind.Destructor) ? "~" + this.Name : (method1.IsConstructor() ? this.Name : method1.Name); // Type '{1}' already defines a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, method1.Locations[0], methodName, this); } private void CheckIndexerNameConflicts(BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName) { PooledHashSet<string>? typeParameterNames = null; if (this.Arity > 0) { typeParameterNames = PooledHashSet<string>.GetInstance(); foreach (TypeParameterSymbol typeParameter in this.TypeParameters) { typeParameterNames.Add(typeParameter.Name); } } var indexersBySignature = new Dictionary<PropertySymbol, PropertySymbol>(MemberSignatureComparer.DuplicateSourceComparer); // Note: Can't assume that all indexers are called WellKnownMemberNames.Indexer because // they may be explicit interface implementations. foreach (var members in membersByName.Values) { string? lastIndexerName = null; indexersBySignature.Clear(); foreach (var symbol in members) { if (symbol.IsIndexer()) { PropertySymbol indexer = (PropertySymbol)symbol; CheckIndexerSignatureCollisions( indexer, diagnostics, membersByName, indexersBySignature, ref lastIndexerName); // Also check for collisions with type parameters, which aren't in the member map. // NOTE: Accessors have normal names and are handled in CheckTypeParameterNameConflicts. if (typeParameterNames != null) { string indexerName = indexer.MetadataName; if (typeParameterNames.Contains(indexerName)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); continue; } } } } } typeParameterNames?.Free(); } private void CheckIndexerSignatureCollisions( PropertySymbol indexer, BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<PropertySymbol, PropertySymbol> indexersBySignature, ref string? lastIndexerName) { if (!indexer.IsExplicitInterfaceImplementation) //explicit implementation names are not checked { string indexerName = indexer.MetadataName; if (lastIndexerName != null && lastIndexerName != indexerName) { // NOTE: dev10 checks indexer names by comparing each to the previous. // For example, if indexers are declared with names A, B, A, B, then there // will be three errors - one for each time the name is different from the // previous one. If, on the other hand, the names are A, A, B, B, then // there will only be one error because only one indexer has a different // name from the previous one. diagnostics.Add(ErrorCode.ERR_InconsistentIndexerNames, indexer.Locations[0]); } lastIndexerName = indexerName; if (Locations.Length == 1 || IsPartial) { if (membersByName.ContainsKey(indexerName)) { // The name of the indexer is reserved - it can only be used by other indexers. Debug.Assert(!membersByName[indexerName].Any(SymbolExtensions.IsIndexer)); diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); } } } if (indexersBySignature.TryGetValue(indexer, out var prevIndexerBySignature)) { // Type '{1}' already defines a member called '{0}' with the same parameter types // NOTE: Dev10 prints "this" as the name of the indexer. diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, indexer.Locations[0], SyntaxFacts.GetText(SyntaxKind.ThisKeyword), this); } else { indexersBySignature[indexer] = indexer; } } private void CheckSpecialMemberErrors(BindingDiagnosticBag diagnostics) { var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary); foreach (var member in this.GetMembersUnordered()) { member.AfterAddingTypeMembersChecks(conversions, diagnostics); } } private void CheckTypeParameterNameConflicts(BindingDiagnosticBag diagnostics) { if (this.TypeKind == TypeKind.Delegate) { // Delegates do not have conflicts between their type parameter // names and their methods; it is legal (though odd) to say // delegate void D<Invoke>(Invoke x); return; } if (Locations.Length == 1 || IsPartial) { foreach (var tp in TypeParameters) { foreach (var dup in GetMembers(tp.Name)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, dup.Locations[0], this, tp.Name); } } } } private void CheckAccessorNameConflicts(BindingDiagnosticBag diagnostics) { // Report errors where property and event accessors // conflict with other members of the same name. foreach (Symbol symbol in this.GetMembersUnordered()) { if (symbol.IsExplicitInterfaceImplementation()) { // If there's a name conflict it will show up as a more specific // interface implementation error. continue; } switch (symbol.Kind) { case SymbolKind.Property: { var propertySymbol = (PropertySymbol)symbol; this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: true, diagnostics: diagnostics); this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: false, diagnostics: diagnostics); break; } case SymbolKind.Event: { var eventSymbol = (EventSymbol)symbol; this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: true, diagnostics: diagnostics); this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: false, diagnostics: diagnostics); break; } } } } internal override bool KnownCircularStruct { get { if (_lazyKnownCircularStruct == (int)ThreeState.Unknown) { if (TypeKind != TypeKind.Struct) { Interlocked.CompareExchange(ref _lazyKnownCircularStruct, (int)ThreeState.False, (int)ThreeState.Unknown); } else { var diagnostics = BindingDiagnosticBag.GetInstance(); var value = (int)CheckStructCircularity(diagnostics).ToThreeState(); if (Interlocked.CompareExchange(ref _lazyKnownCircularStruct, value, (int)ThreeState.Unknown) == (int)ThreeState.Unknown) { AddDeclarationDiagnostics(diagnostics); } Debug.Assert(value == _lazyKnownCircularStruct); diagnostics.Free(); } } return _lazyKnownCircularStruct == (int)ThreeState.True; } } private bool CheckStructCircularity(BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); CheckFiniteFlatteningGraph(diagnostics); return HasStructCircularity(diagnostics); } private bool HasStructCircularity(BindingDiagnosticBag diagnostics) { foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member.Kind != SymbolKind.Field) { // NOTE: don't have to check field-like events, because they can't have struct types. continue; } var field = (FieldSymbol)member; if (field.IsStatic) { continue; } var type = field.NonPointerType(); if (((object)type != null) && (type.TypeKind == TypeKind.Struct) && BaseTypeAnalysis.StructDependsOn((NamedTypeSymbol)type, this) && !type.IsPrimitiveRecursiveStruct()) // allow System.Int32 to contain a field of its own type { // If this is a backing field, report the error on the associated property. var symbol = field.AssociatedSymbol ?? field; if (symbol.Kind == SymbolKind.Parameter) { // We should stick to members for this error. symbol = field; } // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, symbol.Locations[0], symbol, type); return true; } } } return false; } private void CheckForProtectedInStaticClass(BindingDiagnosticBag diagnostics) { if (!IsStatic) { return; } // no protected members allowed foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member is TypeSymbol) { // Duplicate Dev10's failure to diagnose this error. continue; } if (member.DeclaredAccessibility.HasProtected()) { if (member.Kind != SymbolKind.Method || ((MethodSymbol)member).MethodKind != MethodKind.Destructor) { diagnostics.Add(ErrorCode.ERR_ProtectedInStatic, member.Locations[0], member); } } } } } private void CheckForUnmatchedOperators(BindingDiagnosticBag diagnostics) { // SPEC: The true and false unary operators require pairwise declaration. // SPEC: A compile-time error occurs if a class or struct declares one // SPEC: of these operators without also declaring the other. // // SPEC DEFICIENCY: The line of the specification quoted above should say // the same thing as the lines below: that the formal parameters of the // paired true/false operators must match exactly. You can't do // op true(S) and op false(S?) for example. // SPEC: Certain binary operators require pairwise declaration. For every // SPEC: declaration of either operator of a pair, there must be a matching // SPEC: declaration of the other operator of the pair. Two operator // SPEC: declarations match when they have the same return type and the same // SPEC: type for each parameter. The following operators require pairwise // SPEC: declaration: == and !=, > and <, >= and <=. CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.TrueOperatorName, WellKnownMemberNames.FalseOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.EqualityOperatorName, WellKnownMemberNames.InequalityOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOperatorName, WellKnownMemberNames.GreaterThanOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOrEqualOperatorName, WellKnownMemberNames.GreaterThanOrEqualOperatorName); // We also produce a warning if == / != is overridden without also overriding // Equals and GetHashCode, or if Equals is overridden without GetHashCode. CheckForEqualityAndGetHashCode(diagnostics); } private void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, string operatorName1, string operatorName2) { var ops1 = this.GetOperators(operatorName1); var ops2 = this.GetOperators(operatorName2); CheckForUnmatchedOperator(diagnostics, ops1, ops2, operatorName2); CheckForUnmatchedOperator(diagnostics, ops2, ops1, operatorName1); } private static void CheckForUnmatchedOperator( BindingDiagnosticBag diagnostics, ImmutableArray<MethodSymbol> ops1, ImmutableArray<MethodSymbol> ops2, string operatorName2) { foreach (var op1 in ops1) { bool foundMatch = false; foreach (var op2 in ops2) { foundMatch = DoOperatorsPair(op1, op2); if (foundMatch) { break; } } if (!foundMatch) { // CS0216: The operator 'C.operator true(C)' requires a matching operator 'false' to also be defined diagnostics.Add(ErrorCode.ERR_OperatorNeedsMatch, op1.Locations[0], op1, SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName2))); } } } private static bool DoOperatorsPair(MethodSymbol op1, MethodSymbol op2) { if (op1.ParameterCount != op2.ParameterCount) { return false; } for (int p = 0; p < op1.ParameterCount; ++p) { if (!op1.ParameterTypesWithAnnotations[p].Equals(op2.ParameterTypesWithAnnotations[p], TypeCompareKind.AllIgnoreOptions)) { return false; } } if (!op1.ReturnType.Equals(op2.ReturnType, TypeCompareKind.AllIgnoreOptions)) { return false; } return true; } private void CheckForEqualityAndGetHashCode(BindingDiagnosticBag diagnostics) { if (this.IsInterfaceType()) { // Interfaces are allowed to define Equals without GetHashCode if they want. return; } if (IsRecord || IsRecordStruct) { // For records the warnings reported below are simply going to echo record specific errors, // producing more noise. return; } bool hasOp = this.GetOperators(WellKnownMemberNames.EqualityOperatorName).Any() || this.GetOperators(WellKnownMemberNames.InequalityOperatorName).Any(); bool overridesEquals = this.TypeOverridesObjectMethod("Equals"); if (hasOp || overridesEquals) { bool overridesGHC = this.TypeOverridesObjectMethod("GetHashCode"); if (overridesEquals && !overridesGHC) { // CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualsWithoutGetHashCode, this.Locations[0], this); } if (hasOp && !overridesEquals) { // CS0660: 'C' defines operator == or operator != but does not override Object.Equals(object o) diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutEquals, this.Locations[0], this); } if (hasOp && !overridesGHC) { // CS0661: 'C' defines operator == or operator != but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutGetHashCode, this.Locations[0], this); } } } private bool TypeOverridesObjectMethod(string name) { foreach (var method in this.GetMembers(name).OfType<MethodSymbol>()) { if (method.IsOverride && method.GetConstructedLeastOverriddenMethod(this, requireSameReturnType: false).ContainingType.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object) { return true; } } return false; } private void CheckFiniteFlatteningGraph(BindingDiagnosticBag diagnostics) { Debug.Assert(ReferenceEquals(this, this.OriginalDefinition)); if (AllTypeArgumentCount() == 0) return; var instanceMap = new Dictionary<NamedTypeSymbol, NamedTypeSymbol>(ReferenceEqualityComparer.Instance); instanceMap.Add(this, this); foreach (var m in this.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(this, type, instanceMap)) { // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, f.Locations[0], f, type); //this.KnownCircularStruct = true; return; } } } private static bool InfiniteFlatteningGraph(SourceMemberContainerTypeSymbol top, NamedTypeSymbol t, Dictionary<NamedTypeSymbol, NamedTypeSymbol> instanceMap) { if (!t.ContainsTypeParameter()) return false; var tOriginal = t.OriginalDefinition; if (instanceMap.TryGetValue(tOriginal, out var oldInstance)) { // short circuit when we find a cycle, but only return true when the cycle contains the top struct return (!TypeSymbol.Equals(oldInstance, t, TypeCompareKind.AllNullableIgnoreOptions)) && ReferenceEquals(tOriginal, top); } else { instanceMap.Add(tOriginal, t); try { foreach (var m in t.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(top, type, instanceMap)) return true; } return false; } finally { instanceMap.Remove(tOriginal); } } } private void CheckSequentialOnPartialType(BindingDiagnosticBag diagnostics) { if (!IsPartial || this.Layout.Kind != LayoutKind.Sequential) { return; } SyntaxReference? whereFoundField = null; if (this.SyntaxReferences.Length <= 1) { return; } foreach (var syntaxRef in this.SyntaxReferences) { var syntax = syntaxRef.GetSyntax() as TypeDeclarationSyntax; if (syntax == null) { continue; } foreach (var m in syntax.Members) { if (HasInstanceData(m)) { if (whereFoundField != null && whereFoundField != syntaxRef) { diagnostics.Add(ErrorCode.WRN_SequentialOnPartialClass, Locations[0], this); return; } whereFoundField = syntaxRef; } } } } private static bool HasInstanceData(MemberDeclarationSyntax m) { switch (m.Kind()) { case SyntaxKind.FieldDeclaration: var fieldDecl = (FieldDeclarationSyntax)m; return !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.ConstKeyword); case SyntaxKind.PropertyDeclaration: // auto-property var propertyDecl = (PropertyDeclarationSyntax)m; return !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.ExternKeyword) && propertyDecl.AccessorList != null && All(propertyDecl.AccessorList.Accessors, a => a.Body == null && a.ExpressionBody == null); case SyntaxKind.EventFieldDeclaration: // field-like event declaration var eventFieldDecl = (EventFieldDeclarationSyntax)m; return !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.ExternKeyword); default: return false; } } private static bool All<T>(SyntaxList<T> list, Func<T, bool> predicate) where T : CSharpSyntaxNode { foreach (var t in list) { if (predicate(t)) return true; }; return false; } private static bool ContainsModifier(SyntaxTokenList modifiers, SyntaxKind modifier) { foreach (var m in modifiers) { if (m.IsKind(modifier)) return true; }; return false; } private Dictionary<string, ImmutableArray<Symbol>> MakeAllMembers(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName; var membersAndInitializers = GetMembersAndInitializers(); // Most types don't have indexers. If this is one of those types, // just reuse the dictionary we build for early attribute decoding. // For tuples, we also need to take the slow path. if (!membersAndInitializers.HaveIndexers && !this.IsTupleType && _lazyEarlyAttributeDecodingMembersDictionary is object) { membersByName = _lazyEarlyAttributeDecodingMembersDictionary; } else { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name, StringOrdinalComparer.Instance); // Merge types into the member dictionary AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); } MergePartialMembers(ref membersByName, diagnostics); return membersByName; } private static void AddNestedTypesToDictionary(Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<string, ImmutableArray<NamedTypeSymbol>> typesByName) { foreach (var pair in typesByName) { string name = pair.Key; ImmutableArray<NamedTypeSymbol> types = pair.Value; ImmutableArray<Symbol> typesAsSymbols = StaticCast<Symbol>.From(types); ImmutableArray<Symbol> membersForName; if (membersByName.TryGetValue(name, out membersForName)) { membersByName[name] = membersForName.Concat(typesAsSymbols); } else { membersByName.Add(name, typesAsSymbols); } } } private sealed class DeclaredMembersAndInitializersBuilder { public ArrayBuilder<Symbol> NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> StaticInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> InstanceInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public bool HaveIndexers; public RecordDeclarationSyntax? RecordDeclarationWithParameters; public SynthesizedRecordConstructor? RecordPrimaryConstructor; public bool IsNullableEnabledForInstanceConstructorsAndFields; public bool IsNullableEnabledForStaticConstructorsAndFields; public DeclaredMembersAndInitializers ToReadOnlyAndFree(CSharpCompilation compilation) { return new DeclaredMembersAndInitializers( NonTypeMembers.ToImmutableAndFree(), MembersAndInitializersBuilder.ToReadOnlyAndFree(StaticInitializers), MembersAndInitializersBuilder.ToReadOnlyAndFree(InstanceInitializers), HaveIndexers, RecordDeclarationWithParameters, RecordPrimaryConstructor, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields, compilation); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, bool value) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || value; } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } public void Free() { NonTypeMembers.Free(); foreach (var group in StaticInitializers) { group.Free(); } StaticInitializers.Free(); foreach (var group in InstanceInitializers) { group.Free(); } InstanceInitializers.Free(); } internal void AddOrWrapTupleMembers(SourceMemberContainerTypeSymbol type) { this.NonTypeMembers = type.AddOrWrapTupleMembers(this.NonTypeMembers.ToImmutableAndFree()); } } private sealed class SimpleProgramEntryPointInfo { public readonly ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> SimpleProgramEntryPoints; public static readonly SimpleProgramEntryPointInfo UninitializedSentinel = new SimpleProgramEntryPointInfo(); private SimpleProgramEntryPointInfo() { } public SimpleProgramEntryPointInfo(ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> simpleProgramEntryPoints) { Debug.Assert(simpleProgramEntryPoints.All(ep => ep is not null)); this.SimpleProgramEntryPoints = simpleProgramEntryPoints; } } protected sealed class DeclaredMembersAndInitializers { public readonly ImmutableArray<Symbol> NonTypeMembers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; public readonly bool HaveIndexers; public readonly RecordDeclarationSyntax? RecordDeclarationWithParameters; public readonly SynthesizedRecordConstructor? RecordPrimaryConstructor; public readonly bool IsNullableEnabledForInstanceConstructorsAndFields; public readonly bool IsNullableEnabledForStaticConstructorsAndFields; public static readonly DeclaredMembersAndInitializers UninitializedSentinel = new DeclaredMembersAndInitializers(); private DeclaredMembersAndInitializers() { } public DeclaredMembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, RecordDeclarationSyntax? recordDeclarationWithParameters, SynthesizedRecordConstructor? recordPrimaryConstructor, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields, CSharpCompilation compilation) { Debug.Assert(!nonTypeMembers.IsDefault); AssertInitializers(staticInitializers, compilation); AssertInitializers(instanceInitializers, compilation); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(recordDeclarationWithParameters is object == recordPrimaryConstructor is object); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.RecordDeclarationWithParameters = recordDeclarationWithParameters; this.RecordPrimaryConstructor = recordPrimaryConstructor; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } [Conditional("DEBUG")] public static void AssertInitializers(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, CSharpCompilation compilation) { Debug.Assert(!initializers.IsDefault); if (initializers.IsEmpty) { return; } foreach (ImmutableArray<FieldOrPropertyInitializer> group in initializers) { Debug.Assert(!group.IsDefaultOrEmpty); } for (int i = 0; i < initializers.Length; i++) { if (i > 0) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i - 1].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } if (i + 1 < initializers.Length) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i + 1].Last().Syntax, compilation)) < 0); } if (initializers[i].Length != 1) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } } } } private sealed class MembersAndInitializersBuilder { public ArrayBuilder<Symbol>? NonTypeMembers; private ArrayBuilder<FieldOrPropertyInitializer>? InstanceInitializersForPositionalMembers; private bool IsNullableEnabledForInstanceConstructorsAndFields; private bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializersBuilder(DeclaredMembersAndInitializers declaredMembersAndInitializers) { Debug.Assert(declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel); this.IsNullableEnabledForInstanceConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields; } public MembersAndInitializers ToReadOnlyAndFree(DeclaredMembersAndInitializers declaredMembers) { var nonTypeMembers = NonTypeMembers?.ToImmutableAndFree() ?? declaredMembers.NonTypeMembers; var instanceInitializers = InstanceInitializersForPositionalMembers is null ? declaredMembers.InstanceInitializers : mergeInitializers(); return new MembersAndInitializers( nonTypeMembers, declaredMembers.StaticInitializers, instanceInitializers, declaredMembers.HaveIndexers, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields); ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> mergeInitializers() { Debug.Assert(InstanceInitializersForPositionalMembers.Count != 0); Debug.Assert(declaredMembers.RecordPrimaryConstructor is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.SyntaxTree == InstanceInitializersForPositionalMembers[0].Syntax.SyntaxTree); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.Span.Contains(InstanceInitializersForPositionalMembers[0].Syntax.Span.Start)); var groupCount = declaredMembers.InstanceInitializers.Length; if (groupCount == 0) { return ImmutableArray.Create(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); } var compilation = declaredMembers.RecordPrimaryConstructor.DeclaringCompilation; var sortKey = new LexicalSortKey(InstanceInitializersForPositionalMembers.First().Syntax, compilation); int insertAt; for (insertAt = 0; insertAt < groupCount; insertAt++) { if (LexicalSortKey.Compare(sortKey, new LexicalSortKey(declaredMembers.InstanceInitializers[insertAt][0].Syntax, compilation)) < 0) { break; } } ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> groupsBuilder; if (insertAt != groupCount && declaredMembers.RecordDeclarationWithParameters.SyntaxTree == declaredMembers.InstanceInitializers[insertAt][0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(declaredMembers.InstanceInitializers[insertAt][0].Syntax.Span.Start)) { // Need to merge into the previous group var declaredInitializers = declaredMembers.InstanceInitializers[insertAt]; var insertedInitializers = InstanceInitializersForPositionalMembers; #if DEBUG // initializers should be added in syntax order: Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.SyntaxTree == declaredInitializers[0].Syntax.SyntaxTree); Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.Span.Start < declaredInitializers[0].Syntax.Span.Start); #endif insertedInitializers.AddRange(declaredInitializers); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(insertedInitializers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt + 1, groupCount - (insertAt + 1)); Debug.Assert(groupsBuilder.Count == groupCount); } else { Debug.Assert(!declaredMembers.InstanceInitializers.Any(g => declaredMembers.RecordDeclarationWithParameters.SyntaxTree == g[0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(g[0].Syntax.Span.Start))); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount + 1); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt, groupCount - insertAt); Debug.Assert(groupsBuilder.Count == groupCount + 1); } var result = groupsBuilder.ToImmutableAndFree(); DeclaredMembersAndInitializers.AssertInitializers(result, compilation); return result; } } public void AddInstanceInitializerForPositionalMembers(FieldOrPropertyInitializer initializer) { if (InstanceInitializersForPositionalMembers is null) { InstanceInitializersForPositionalMembers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } InstanceInitializersForPositionalMembers.Add(initializer); } public IReadOnlyCollection<Symbol> GetNonTypeMembers(DeclaredMembersAndInitializers declaredMembers) { return NonTypeMembers ?? (IReadOnlyCollection<Symbol>)declaredMembers.NonTypeMembers; } public void AddNonTypeMember(Symbol member, DeclaredMembersAndInitializers declaredMembers) { if (NonTypeMembers is null) { NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(declaredMembers.NonTypeMembers.Length + 1); NonTypeMembers.AddRange(declaredMembers.NonTypeMembers); } NonTypeMembers.Add(member); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } internal static ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> ToReadOnlyAndFree(ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> initializers) { if (initializers.Count == 0) { initializers.Free(); return ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>>.Empty; } var builder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(initializers.Count); foreach (ArrayBuilder<FieldOrPropertyInitializer> group in initializers) { builder.Add(group.ToImmutableAndFree()); } initializers.Free(); return builder.ToImmutableAndFree(); } public void Free() { NonTypeMembers?.Free(); InstanceInitializersForPositionalMembers?.Free(); } } protected MembersAndInitializers? BuildMembersAndInitializers(BindingDiagnosticBag diagnostics) { var declaredMembersAndInitializers = getDeclaredMembersAndInitializers(); if (declaredMembersAndInitializers is null) { // Another thread completed the work before this one return null; } var membersAndInitializersBuilder = new MembersAndInitializersBuilder(declaredMembersAndInitializers); AddSynthesizedMembers(membersAndInitializersBuilder, declaredMembersAndInitializers, diagnostics); if (Volatile.Read(ref _lazyMembersAndInitializers) != null) { // Another thread completed the work before this one membersAndInitializersBuilder.Free(); return null; } return membersAndInitializersBuilder.ToReadOnlyAndFree(declaredMembersAndInitializers); DeclaredMembersAndInitializers? getDeclaredMembersAndInitializers() { var declaredMembersAndInitializers = _lazyDeclaredMembersAndInitializers; if (declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel) { return declaredMembersAndInitializers; } if (Volatile.Read(ref _lazyMembersAndInitializers) is not null) { // We're previously computed declared members and already cleared them out // No need to compute them again return null; } var diagnostics = BindingDiagnosticBag.GetInstance(); declaredMembersAndInitializers = buildDeclaredMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyDeclaredMembersAndInitializers, declaredMembersAndInitializers, DeclaredMembersAndInitializers.UninitializedSentinel); if (alreadyKnown != DeclaredMembersAndInitializers.UninitializedSentinel) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); return declaredMembersAndInitializers!; } // Builds explicitly declared members (as opposed to synthesized members). // This should not attempt to bind any method parameters as that would cause // the members being built to be captured in the binder cache before the final // list of members is determined. DeclaredMembersAndInitializers? buildDeclaredMembersAndInitializers(BindingDiagnosticBag diagnostics) { var builder = new DeclaredMembersAndInitializersBuilder(); AddDeclaredNontypeMembers(builder, diagnostics); switch (TypeKind) { case TypeKind.Struct: CheckForStructBadInitializers(builder, diagnostics); CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: false, diagnostics: diagnostics); break; case TypeKind.Enum: CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: true, diagnostics: diagnostics); break; case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: // No additional checking required. break; default: break; } if (IsTupleType) { builder.AddOrWrapTupleMembers(this); } if (Volatile.Read(ref _lazyDeclaredMembersAndInitializers) != DeclaredMembersAndInitializers.UninitializedSentinel) { // _lazyDeclaredMembersAndInitializers is already computed. no point to continue. builder.Free(); return null; } return builder.ToReadOnlyAndFree(DeclaringCompilation); } } internal ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> GetSimpleProgramEntryPoints() { if (this.ContainingSymbol is not NamespaceSymbol { IsGlobalNamespace: true } || this.Name != WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) { return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; } SimpleProgramEntryPointInfo? simpleProgramEntryPointInfo = _lazySimpleProgramEntryPoint; if (simpleProgramEntryPointInfo == SimpleProgramEntryPointInfo.UninitializedSentinel) { var diagnostics = BindingDiagnosticBag.GetInstance(); simpleProgramEntryPointInfo = buildSimpleProgramEntryPoint(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazySimpleProgramEntryPoint, simpleProgramEntryPointInfo, SimpleProgramEntryPointInfo.UninitializedSentinel); if (alreadyKnown == SimpleProgramEntryPointInfo.UninitializedSentinel) { AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _lazySimpleProgramEntryPoint?.SimpleProgramEntryPoints ?? ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; SimpleProgramEntryPointInfo? buildSimpleProgramEntryPoint(BindingDiagnosticBag diagnostics) { ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>? builder = null; foreach (var singleDecl in declaration.Declarations) { if (singleDecl.IsSimpleProgram) { if (builder is null) { builder = ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>.GetInstance(); } else { Binder.Error(diagnostics, ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, singleDecl.NameLocation); } builder.Add(new SynthesizedSimpleProgramEntryPointSymbol(this, singleDecl, diagnostics)); } } if (builder is null) { return null; } return new SimpleProgramEntryPointInfo(builder.ToImmutableAndFree()); } } private void AddSynthesizedMembers(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (TypeKind is TypeKind.Class) { AddSynthesizedSimpleProgramEntryPointIfNecessary(builder, declaredMembersAndInitializers, diagnostics); } switch (TypeKind) { case TypeKind.Struct: case TypeKind.Enum: case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: AddSynthesizedRecordMembersIfNecessary(builder, declaredMembersAndInitializers, diagnostics); AddSynthesizedConstructorsIfNecessary(builder, declaredMembersAndInitializers, diagnostics); break; default: break; } } private void AddDeclaredNontypeMembers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { foreach (var decl in this.declaration.Declarations) { if (!decl.HasAnyNontypeMembers) { continue; } if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } var syntax = decl.SyntaxReference.GetSyntax(); switch (syntax.Kind()) { case SyntaxKind.EnumDeclaration: AddEnumMembers(builder, (EnumDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.DelegateDeclaration: SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeMembers, (DelegateDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // The members of a global anonymous type is in a syntax tree of a namespace declaration or a compilation unit. AddNonTypeMembers(builder, ((BaseNamespaceDeclarationSyntax)syntax).Members, diagnostics); break; case SyntaxKind.CompilationUnit: AddNonTypeMembers(builder, ((CompilationUnitSyntax)syntax).Members, diagnostics); break; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)syntax; AddNonTypeMembers(builder, typeDecl.Members, diagnostics); break; case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var recordDecl = (RecordDeclarationSyntax)syntax; var parameterList = recordDecl.ParameterList; noteRecordParameters(recordDecl, parameterList, builder, diagnostics); AddNonTypeMembers(builder, recordDecl.Members, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } void noteRecordParameters(RecordDeclarationSyntax syntax, ParameterListSyntax? parameterList, DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { if (parameterList is null) { return; } if (builder.RecordDeclarationWithParameters is null) { builder.RecordDeclarationWithParameters = syntax; var ctor = new SynthesizedRecordConstructor(this, syntax); builder.RecordPrimaryConstructor = ctor; var compilation = DeclaringCompilation; builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, parameterList); if (syntax is { PrimaryConstructorBaseTypeIfClass: { ArgumentList: { } baseParamList } }) { builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, baseParamList); } } else { diagnostics.Add(ErrorCode.ERR_MultipleRecordParameterLists, parameterList.Location); } } } internal Binder GetBinder(CSharpSyntaxNode syntaxNode) { return this.DeclaringCompilation.GetBinder(syntaxNode); } private void MergePartialMembers( ref Dictionary<string, ImmutableArray<Symbol>> membersByName, BindingDiagnosticBag diagnostics) { var memberNames = ArrayBuilder<string>.GetInstance(membersByName.Count); memberNames.AddRange(membersByName.Keys); //key and value will be the same object var methodsBySignature = new Dictionary<MethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.PartialMethodsComparer); foreach (var name in memberNames) { methodsBySignature.Clear(); foreach (var symbol in membersByName[name]) { var method = symbol as SourceMemberMethodSymbol; if (method is null || !method.IsPartial) { continue; // only partial methods need to be merged } if (methodsBySignature.TryGetValue(method, out var prev)) { var prevPart = (SourceOrdinaryMethodSymbol)prev; var methodPart = (SourceOrdinaryMethodSymbol)method; if (methodPart.IsPartialImplementation && (prevPart.IsPartialImplementation || (prevPart.OtherPartOfPartial is MethodSymbol otherImplementation && (object)otherImplementation != methodPart))) { // A partial method may not have multiple implementing declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneActual, methodPart.Locations[0]); } else if (methodPart.IsPartialDefinition && (prevPart.IsPartialDefinition || (prevPart.OtherPartOfPartial is MethodSymbol otherDefinition && (object)otherDefinition != methodPart))) { // A partial method may not have multiple defining declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneLatent, methodPart.Locations[0]); } else { if ((object)membersByName == _lazyEarlyAttributeDecodingMembersDictionary) { // Avoid mutating the cached dictionary and especially avoid doing this possibly on multiple threads in parallel. membersByName = new Dictionary<string, ImmutableArray<Symbol>>(membersByName); } membersByName[name] = FixPartialMember(membersByName[name], prevPart, methodPart); } } else { methodsBySignature.Add(method, method); } } foreach (SourceOrdinaryMethodSymbol method in methodsBySignature.Values) { // partial implementations not paired with a definition if (method.IsPartialImplementation && method.OtherPartOfPartial is null) { diagnostics.Add(ErrorCode.ERR_PartialMethodMustHaveLatent, method.Locations[0], method); } else if (method is { IsPartialDefinition: true, OtherPartOfPartial: null, HasExplicitAccessModifier: true }) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, method.Locations[0], method); } } } memberNames.Free(); } /// <summary> /// Fix up a partial method by combining its defining and implementing declarations, updating the array of symbols (by name), /// and returning the combined symbol. /// </summary> /// <param name="symbols">The symbols array containing both the latent and implementing declaration</param> /// <param name="part1">One of the two declarations</param> /// <param name="part2">The other declaration</param> /// <returns>An updated symbols array containing only one method symbol representing the two parts</returns> private static ImmutableArray<Symbol> FixPartialMember(ImmutableArray<Symbol> symbols, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2) { SourceOrdinaryMethodSymbol definition; SourceOrdinaryMethodSymbol implementation; if (part1.IsPartialDefinition) { definition = part1; implementation = part2; } else { definition = part2; implementation = part1; } SourceOrdinaryMethodSymbol.InitializePartialMethodParts(definition, implementation); // a partial method is represented in the member list by its definition part: return Remove(symbols, implementation); } private static ImmutableArray<Symbol> Remove(ImmutableArray<Symbol> symbols, Symbol symbol) { var builder = ArrayBuilder<Symbol>.GetInstance(); foreach (var s in symbols) { if (!ReferenceEquals(s, symbol)) { builder.Add(s); } } return builder.ToImmutableAndFree(); } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the property accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithPropertyAccessor( PropertySymbol propertySymbol, bool getNotSet, BindingDiagnosticBag diagnostics) { Debug.Assert(!propertySymbol.IsExplicitInterfaceImplementation); // checked by caller MethodSymbol accessor = getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod; string accessorName; if ((object)accessor != null) { accessorName = accessor.Name; } else { string propertyName = propertySymbol.IsIndexer ? propertySymbol.MetadataName : propertySymbol.Name; accessorName = SourcePropertyAccessorSymbol.GetAccessorName(propertyName, getNotSet, propertySymbol.IsCompilationOutputWinMdObj()); } foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchPropertyAccessor(propertySymbol, getNotSet, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), accessorName, this); return; } } } } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the event accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithEventAccessor( EventSymbol eventSymbol, bool isAdder, BindingDiagnosticBag diagnostics) { Debug.Assert(!eventSymbol.IsExplicitInterfaceImplementation); // checked by caller string accessorName = SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAdder); foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrEventLocation(eventSymbol, isAdder), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchEventAccessor(eventSymbol, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrEventLocation(eventSymbol, isAdder), accessorName, this); return; } } } } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the property. /// </summary> private static Location GetAccessorOrPropertyLocation(PropertySymbol propertySymbol, bool getNotSet) { var locationFrom = (Symbol)(getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the event. /// </summary> private static Location GetAccessorOrEventLocation(EventSymbol propertySymbol, bool isAdder) { var locationFrom = (Symbol?)(isAdder ? propertySymbol.AddMethod : propertySymbol.RemoveMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return true if the method parameters match the parameters of the /// property accessor, including the value parameter for the setter. /// </summary> private static bool ParametersMatchPropertyAccessor(PropertySymbol propertySymbol, bool getNotSet, ImmutableArray<ParameterSymbol> methodParams) { var propertyParams = propertySymbol.Parameters; var numParams = propertyParams.Length + (getNotSet ? 0 : 1); if (numParams != methodParams.Length) { return false; } for (int i = 0; i < numParams; i++) { var methodParam = methodParams[i]; if (methodParam.RefKind != RefKind.None) { return false; } var propertyParamType = (((i == numParams - 1) && !getNotSet) ? propertySymbol.TypeWithAnnotations : propertyParams[i].TypeWithAnnotations).Type; if (!propertyParamType.Equals(methodParam.Type, TypeCompareKind.AllIgnoreOptions)) { return false; } } return true; } /// <summary> /// Return true if the method parameters match the parameters of the /// event accessor, including the value parameter. /// </summary> private static bool ParametersMatchEventAccessor(EventSymbol eventSymbol, ImmutableArray<ParameterSymbol> methodParams) { return methodParams.Length == 1 && methodParams[0].RefKind == RefKind.None && eventSymbol.Type.Equals(methodParams[0].Type, TypeCompareKind.AllIgnoreOptions); } private void AddEnumMembers(DeclaredMembersAndInitializersBuilder result, EnumDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { // The previous enum constant used to calculate subsequent // implicit enum constants. (This is the most recent explicit // enum constant or the first implicit constant if no explicit values.) SourceEnumConstantSymbol? otherSymbol = null; // Offset from "otherSymbol". int otherSymbolOffset = 0; foreach (var member in syntax.Members) { SourceEnumConstantSymbol symbol; var valueOpt = member.EqualsValue; if (valueOpt != null) { symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(this, member, diagnostics); } else { symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(this, member, otherSymbol, otherSymbolOffset, diagnostics); } result.NonTypeMembers.Add(symbol); if (valueOpt != null || otherSymbol is null) { otherSymbol = symbol; otherSymbolOffset = 1; } else { otherSymbolOffset++; } } } private static void AddInitializer(ref ArrayBuilder<FieldOrPropertyInitializer>? initializers, FieldSymbol? fieldOpt, CSharpSyntaxNode node) { if (initializers == null) { initializers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } else if (initializers.Count != 0) { // initializers should be added in syntax order: Debug.Assert(node.SyntaxTree == initializers.Last().Syntax.SyntaxTree); Debug.Assert(node.SpanStart > initializers.Last().Syntax.Span.Start); } initializers.Add(new FieldOrPropertyInitializer(fieldOpt, node)); } private static void AddInitializers( ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> allInitializers, ArrayBuilder<FieldOrPropertyInitializer>? siblingsOpt) { if (siblingsOpt != null) { allInitializers.Add(siblingsOpt); } } private static void CheckInterfaceMembers(ImmutableArray<Symbol> nonTypeMembers, BindingDiagnosticBag diagnostics) { foreach (var member in nonTypeMembers) { CheckInterfaceMember(member, diagnostics); } } private static void CheckInterfaceMember(Symbol member, BindingDiagnosticBag diagnostics) { switch (member.Kind) { case SymbolKind.Field: break; case SymbolKind.Method: var meth = (MethodSymbol)member; switch (meth.MethodKind) { case MethodKind.Constructor: diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConstructors, member.Locations[0]); break; case MethodKind.Conversion: if (!meth.IsAbstract) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.UserDefinedOperator: if (!meth.IsAbstract && (meth.Name == WellKnownMemberNames.EqualityOperatorName || meth.Name == WellKnownMemberNames.InequalityOperatorName)) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.Destructor: diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, member.Locations[0]); break; case MethodKind.ExplicitInterfaceImplementation: //CS0541 is handled in SourcePropertySymbol case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRemove: case MethodKind.StaticConstructor: break; default: throw ExceptionUtilities.UnexpectedValue(meth.MethodKind); } break; case SymbolKind.Property: break; case SymbolKind.Event: break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private static void CheckForStructDefaultConstructors( ArrayBuilder<Symbol> members, bool isEnum, BindingDiagnosticBag diagnostics) { foreach (var s in members) { var m = s as MethodSymbol; if (!(m is null)) { if (m.MethodKind == MethodKind.Constructor && m.ParameterCount == 0) { var location = m.Locations[0]; if (isEnum) { diagnostics.Add(ErrorCode.ERR_EnumsCantContainDefaultConstructor, location); } else { MessageID.IDS_FeatureParameterlessStructConstructors.CheckFeatureAvailability(diagnostics, m.DeclaringCompilation, location); if (m.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicParameterlessStructConstructor, location); } } } } } } private void CheckForStructBadInitializers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); if (builder.RecordDeclarationWithParameters is not null) { Debug.Assert(builder.RecordDeclarationWithParameters is RecordDeclarationSyntax { ParameterList: not null } record && record.Kind() == SyntaxKind.RecordStructDeclaration); return; } foreach (var initializers in builder.InstanceInitializers) { foreach (FieldOrPropertyInitializer initializer in initializers) { var symbol = initializer.FieldOpt.AssociatedSymbol ?? initializer.FieldOpt; MessageID.IDS_FeatureStructFieldInitializers.CheckFeatureAvailability(diagnostics, symbol.DeclaringCompilation, symbol.Locations[0]); } } } private void AddSynthesizedSimpleProgramEntryPointIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { var simpleProgramEntryPoints = GetSimpleProgramEntryPoints(); foreach (var member in simpleProgramEntryPoints) { builder.AddNonTypeMember(member, declaredMembersAndInitializers); } } private void AddSynthesizedRecordMembersIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (declaration.Kind is not (DeclarationKind.Record or DeclarationKind.RecordStruct)) { return; } ParameterListSyntax? paramList = declaredMembersAndInitializers.RecordDeclarationWithParameters?.ParameterList; var memberSignatures = s_duplicateRecordMemberSignatureDictionary.Allocate(); var fieldsByName = PooledDictionary<string, Symbol>.GetInstance(); var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); var members = ArrayBuilder<Symbol>.GetInstance(membersSoFar.Count + 1); var memberNames = PooledHashSet<string>.GetInstance(); foreach (var member in membersSoFar) { memberNames.Add(member.Name); switch (member) { case EventSymbol: case MethodSymbol { MethodKind: not (MethodKind.Ordinary or MethodKind.Constructor) }: continue; case FieldSymbol { Name: var fieldName }: if (!fieldsByName.ContainsKey(fieldName)) { fieldsByName.Add(fieldName, member); } continue; } if (!memberSignatures.ContainsKey(member)) { memberSignatures.Add(member, member); } } CSharpCompilation compilation = this.DeclaringCompilation; bool isRecordClass = declaration.Kind == DeclarationKind.Record; // Positional record bool primaryAndCopyCtorAmbiguity = false; if (!(paramList is null)) { Debug.Assert(declaredMembersAndInitializers.RecordDeclarationWithParameters is object); // primary ctor var ctor = declaredMembersAndInitializers.RecordPrimaryConstructor; Debug.Assert(ctor is object); members.Add(ctor); if (ctor.ParameterCount != 0) { // properties and Deconstruct var existingOrAddedMembers = addProperties(ctor.Parameters); addDeconstruct(ctor, existingOrAddedMembers); } if (isRecordClass) { primaryAndCopyCtorAmbiguity = ctor.ParameterCount == 1 && ctor.Parameters[0].Type.Equals(this, TypeCompareKind.AllIgnoreOptions); } } if (isRecordClass) { addCopyCtor(primaryAndCopyCtorAmbiguity); addCloneMethod(); } PropertySymbol? equalityContract = isRecordClass ? addEqualityContract() : null; var thisEquals = addThisEquals(equalityContract); if (isRecordClass) { addBaseEquals(); } addObjectEquals(thisEquals); var getHashCode = addGetHashCode(equalityContract); addEqualityOperators(); if (thisEquals is not SynthesizedRecordEquals && getHashCode is SynthesizedRecordGetHashCode) { diagnostics.Add(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, thisEquals.Locations[0], declaration.Name); } var printMembers = addPrintMembersMethod(); addToStringMethod(printMembers); memberSignatures.Free(); fieldsByName.Free(); memberNames.Free(); // We put synthesized record members first so that errors about conflicts show up on user-defined members rather than all // going to the record declaration members.AddRange(membersSoFar); builder.NonTypeMembers?.Free(); builder.NonTypeMembers = members; return; void addDeconstruct(SynthesizedRecordConstructor ctor, ImmutableArray<Symbol> positionalMembers) { Debug.Assert(positionalMembers.All(p => p is PropertySymbol or FieldSymbol)); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.DeconstructMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ctor.Parameters.SelectAsArray<ParameterSymbol, ParameterSymbol>(param => new SignatureOnlyParameterSymbol(param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.Out )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingDeconstructMethod)) { members.Add(new SynthesizedRecordDeconstruct(this, ctor, positionalMembers, memberOffset: members.Count, diagnostics)); } else { var deconstruct = (MethodSymbol)existingDeconstructMethod; if (deconstruct.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, deconstruct.Locations[0], deconstruct); } if (deconstruct.ReturnType.SpecialType != SpecialType.System_Void && !deconstruct.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, deconstruct.Locations[0], deconstruct, targetMethod.ReturnType); } if (deconstruct.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, deconstruct.Locations[0], deconstruct); } } } void addCopyCtor(bool primaryAndCopyCtorAmbiguity) { Debug.Assert(isRecordClass); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.InstanceConstructorName, this, MethodKind.Constructor, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingConstructor)) { var copyCtor = new SynthesizedRecordCopyCtor(this, memberOffset: members.Count); members.Add(copyCtor); if (primaryAndCopyCtorAmbiguity) { diagnostics.Add(ErrorCode.ERR_RecordAmbigCtor, copyCtor.Locations[0]); } } else { var constructor = (MethodSymbol)existingConstructor; if (!this.IsSealed && (constructor.DeclaredAccessibility != Accessibility.Public && constructor.DeclaredAccessibility != Accessibility.Protected)) { diagnostics.Add(ErrorCode.ERR_CopyConstructorWrongAccessibility, constructor.Locations[0], constructor); } } } void addCloneMethod() { Debug.Assert(isRecordClass); members.Add(new SynthesizedRecordClone(this, memberOffset: members.Count, diagnostics)); } MethodSymbol addPrintMembersMethod() { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.PrintMembersMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Text_StringBuilder)), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None)), RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); MethodSymbol printMembersMethod; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingPrintMembersMethod)) { printMembersMethod = new SynthesizedRecordPrintMembers(this, memberOffset: members.Count, diagnostics); members.Add(printMembersMethod); } else { printMembersMethod = (MethodSymbol)existingPrintMembersMethod; if (!isRecordClass || (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType())) { if (printMembersMethod.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } } else if (printMembersMethod.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } if (!printMembersMethod.ReturnType.Equals(targetMethod.ReturnType, TypeCompareKind.AllIgnoreOptions)) { if (!printMembersMethod.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, printMembersMethod.Locations[0], printMembersMethod, targetMethod.ReturnType); } } else if (isRecordClass) { SynthesizedRecordPrintMembers.VerifyOverridesPrintMembersFromBase(printMembersMethod, diagnostics); } reportStaticOrNotOverridableAPIInRecord(printMembersMethod, diagnostics); } return printMembersMethod; } void addToStringMethod(MethodSymbol printMethod) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectToString, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_String)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); var baseToStringMethod = getBaseToStringMethod(); if (baseToStringMethod is { IsSealed: true }) { if (baseToStringMethod.ContainingModule != this.ContainingModule && !this.DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureSealedToStringInRecord)) { var languageVersion = ((CSharpParseOptions)this.Locations[0].SourceTree!.Options).LanguageVersion; var requiredVersion = MessageID.IDS_FeatureSealedToStringInRecord.RequiredVersion(); diagnostics.Add( ErrorCode.ERR_InheritingFromRecordWithSealedToString, this.Locations[0], languageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } else { if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingToStringMethod)) { var toStringMethod = new SynthesizedRecordToString(this, printMethod, memberOffset: members.Count, diagnostics); members.Add(toStringMethod); } else { var toStringMethod = (MethodSymbol)existingToStringMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(toStringMethod, SpecialMember.System_Object__ToString, diagnostics) && toStringMethod.IsSealed && !IsSealed) { MessageID.IDS_FeatureSealedToStringInRecord.CheckFeatureAvailability( diagnostics, this.DeclaringCompilation, toStringMethod.Locations[0]); } } } MethodSymbol? getBaseToStringMethod() { var objectToString = this.DeclaringCompilation.GetSpecialTypeMember(SpecialMember.System_Object__ToString); var currentBaseType = this.BaseTypeNoUseSiteDiagnostics; while (currentBaseType is not null) { foreach (var member in currentBaseType.GetSimpleNonTypeMembers(WellKnownMemberNames.ObjectToString)) { if (member is not MethodSymbol method) continue; if (method.GetLeastOverriddenMethod(null) == objectToString) return method; } currentBaseType = currentBaseType.BaseTypeNoUseSiteDiagnostics; } return null; } } ImmutableArray<Symbol> addProperties(ImmutableArray<ParameterSymbol> recordParameters) { var existingOrAddedMembers = ArrayBuilder<Symbol>.GetInstance(recordParameters.Length); int addedCount = 0; foreach (ParameterSymbol param in recordParameters) { bool isInherited = false; var syntax = param.GetNonNullSyntaxNode(); var targetProperty = new SignatureOnlyPropertySymbol(param.Name, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); if (!memberSignatures.TryGetValue(targetProperty, out var existingMember) && !fieldsByName.TryGetValue(param.Name, out existingMember)) { existingMember = OverriddenOrHiddenMembersHelpers.FindFirstHiddenMemberIfAny(targetProperty, memberIsFromSomeCompilation: true); isInherited = true; } // There should be an error if we picked a member that is hidden // This will be fixed in C# 9 as part of 16.10. Tracked by https://github.com/dotnet/roslyn/issues/52630 if (existingMember is null) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: false, diagnostics)); } else if (existingMember is FieldSymbol { IsStatic: false } field && field.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { Binder.CheckFeatureAvailability(syntax, MessageID.IDS_FeaturePositionalFieldsInRecords, diagnostics); if (!isInherited || checkMemberNotHidden(field, param)) { existingOrAddedMembers.Add(field); } } else if (existingMember is PropertySymbol { IsStatic: false, GetMethod: { } } prop && prop.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { // There already exists a member corresponding to the candidate synthesized property. if (isInherited && prop.IsAbstract) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: true, diagnostics)); } else if (!isInherited || checkMemberNotHidden(prop, param)) { // Deconstruct() is specified to simply assign from this property to the corresponding out parameter. existingOrAddedMembers.Add(prop); } } else { diagnostics.Add(ErrorCode.ERR_BadRecordMemberForPositionalParameter, param.Locations[0], new FormattedSymbol(existingMember, SymbolDisplayFormat.CSharpErrorMessageFormat.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType)), param.TypeWithAnnotations, param.Name); } void addProperty(SynthesizedRecordPropertySymbol property) { existingOrAddedMembers.Add(property); members.Add(property); Debug.Assert(property.GetMethod is object); Debug.Assert(property.SetMethod is object); members.Add(property.GetMethod); members.Add(property.SetMethod); members.Add(property.BackingField); builder.AddInstanceInitializerForPositionalMembers(new FieldOrPropertyInitializer(property.BackingField, paramList.Parameters[param.Ordinal])); addedCount++; } } return existingOrAddedMembers.ToImmutableAndFree(); bool checkMemberNotHidden(Symbol symbol, ParameterSymbol param) { if (memberNames.Contains(symbol.Name) || this.GetTypeMembersDictionary().ContainsKey(symbol.Name)) { diagnostics.Add(ErrorCode.ERR_HiddenPositionalMember, param.Locations[0], symbol); return false; } return true; } } void addObjectEquals(MethodSymbol thisEquals) { members.Add(new SynthesizedRecordObjEquals(this, thisEquals, memberOffset: members.Count, diagnostics)); } MethodSymbol addGetHashCode(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectGetHashCode, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol getHashCode; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingHashCodeMethod)) { getHashCode = new SynthesizedRecordGetHashCode(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(getHashCode); } else { getHashCode = (MethodSymbol)existingHashCodeMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(getHashCode, SpecialMember.System_Object__GetHashCode, diagnostics) && getHashCode.IsSealed && !IsSealed) { diagnostics.Add(ErrorCode.ERR_SealedAPIInRecord, getHashCode.Locations[0], getHashCode); } } return getHashCode; } PropertySymbol addEqualityContract() { Debug.Assert(isRecordClass); var targetProperty = new SignatureOnlyPropertySymbol(SynthesizedRecordEqualityContractProperty.PropertyName, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Type)), ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); PropertySymbol equalityContract; if (!memberSignatures.TryGetValue(targetProperty, out Symbol? existingEqualityContractProperty)) { equalityContract = new SynthesizedRecordEqualityContractProperty(this, diagnostics); members.Add(equalityContract); members.Add(equalityContract.GetMethod); } else { equalityContract = (PropertySymbol)existingEqualityContractProperty; if (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { if (equalityContract.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, equalityContract.Locations[0], equalityContract); } } else if (equalityContract.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, equalityContract.Locations[0], equalityContract); } if (!equalityContract.Type.Equals(targetProperty.Type, TypeCompareKind.AllIgnoreOptions)) { if (!equalityContract.Type.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, equalityContract.Locations[0], equalityContract, targetProperty.Type); } } else { SynthesizedRecordEqualityContractProperty.VerifyOverridesEqualityContractFromBase(equalityContract, diagnostics); } if (equalityContract.GetMethod is null) { diagnostics.Add(ErrorCode.ERR_EqualityContractRequiresGetter, equalityContract.Locations[0], equalityContract); } reportStaticOrNotOverridableAPIInRecord(equalityContract, diagnostics); } return equalityContract; } MethodSymbol addThisEquals(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectEquals, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol thisEquals; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingEqualsMethod)) { thisEquals = new SynthesizedRecordEquals(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(thisEquals); } else { thisEquals = (MethodSymbol)existingEqualsMethod; if (thisEquals.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, thisEquals.Locations[0], thisEquals); } if (thisEquals.ReturnType.SpecialType != SpecialType.System_Boolean && !thisEquals.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, thisEquals.Locations[0], thisEquals, targetMethod.ReturnType); } reportStaticOrNotOverridableAPIInRecord(thisEquals, diagnostics); } return thisEquals; } void reportStaticOrNotOverridableAPIInRecord(Symbol symbol, BindingDiagnosticBag diagnostics) { if (isRecordClass && !IsSealed && ((!symbol.IsAbstract && !symbol.IsVirtual && !symbol.IsOverride) || symbol.IsSealed)) { diagnostics.Add(ErrorCode.ERR_NotOverridableAPIInRecord, symbol.Locations[0], symbol); } else if (symbol.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, symbol.Locations[0], symbol); } } void addBaseEquals() { Debug.Assert(isRecordClass); if (!BaseTypeNoUseSiteDiagnostics.IsObjectType()) { members.Add(new SynthesizedRecordBaseEquals(this, memberOffset: members.Count, diagnostics)); } } void addEqualityOperators() { members.Add(new SynthesizedRecordEqualityOperator(this, memberOffset: members.Count, diagnostics)); members.Add(new SynthesizedRecordInequalityOperator(this, memberOffset: members.Count, diagnostics)); } } private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { //we're not calling the helpers on NamedTypeSymbol base, because those call //GetMembers and we're inside a GetMembers call ourselves (i.e. stack overflow) var hasInstanceConstructor = false; var hasParameterlessInstanceConstructor = false; var hasStaticConstructor = false; // CONSIDER: if this traversal becomes a bottleneck, the flags could be made outputs of the // dictionary construction process. For now, this is more encapsulated. var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); foreach (var member in membersSoFar) { if (member.Kind == SymbolKind.Method) { var method = (MethodSymbol)member; switch (method.MethodKind) { case MethodKind.Constructor: // Ignore the record copy constructor if (!IsRecord || !(SynthesizedRecordCopyCtor.HasCopyConstructorSignature(method) && method is not SynthesizedRecordConstructor)) { hasInstanceConstructor = true; hasParameterlessInstanceConstructor = hasParameterlessInstanceConstructor || method.ParameterCount == 0; } break; case MethodKind.StaticConstructor: hasStaticConstructor = true; break; } } //kick out early if we've seen everything we're looking for if (hasInstanceConstructor && hasStaticConstructor) { break; } } // NOTE: Per section 11.3.8 of the spec, "every struct implicitly has a parameterless instance constructor". // We won't insert a parameterless constructor for a struct if there already is one. // The synthesized constructor will only be emitted if there are field initializers, but it should be in the symbol table. if ((!hasParameterlessInstanceConstructor && this.IsStructType()) || (!hasInstanceConstructor && !this.IsStatic && !this.IsInterface)) { builder.AddNonTypeMember((this.TypeKind == TypeKind.Submission) ? new SynthesizedSubmissionConstructor(this, diagnostics) : new SynthesizedInstanceConstructor(this), declaredMembersAndInitializers); } // constants don't count, since they do not exist as fields at runtime // NOTE: even for decimal constants (which require field initializers), // we do not create .cctor here since a static constructor implicitly created for a decimal // should not appear in the list returned by public API like GetMembers(). if (!hasStaticConstructor && hasNonConstantInitializer(declaredMembersAndInitializers.StaticInitializers)) { // Note: we don't have to put anything in the method - the binder will // do that when processing field initializers. builder.AddNonTypeMember(new SynthesizedStaticConstructor(this), declaredMembersAndInitializers); } if (this.IsScriptClass) { var scriptInitializer = new SynthesizedInteractiveInitializerMethod(this, diagnostics); builder.AddNonTypeMember(scriptInitializer, declaredMembersAndInitializers); var scriptEntryPoint = SynthesizedEntryPointSymbol.Create(scriptInitializer, diagnostics); builder.AddNonTypeMember(scriptEntryPoint, declaredMembersAndInitializers); } static bool hasNonConstantInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { return initializers.Any(siblings => siblings.Any(initializer => !initializer.FieldOpt.IsConst)); } } private void AddNonTypeMembers( DeclaredMembersAndInitializersBuilder builder, SyntaxList<MemberDeclarationSyntax> members, BindingDiagnosticBag diagnostics) { if (members.Count == 0) { return; } var firstMember = members[0]; var bodyBinder = this.GetBinder(firstMember); ArrayBuilder<FieldOrPropertyInitializer>? staticInitializers = null; ArrayBuilder<FieldOrPropertyInitializer>? instanceInitializers = null; var compilation = DeclaringCompilation; foreach (var m in members) { if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } bool reportMisplacedGlobalCode = !m.HasErrors; switch (m.Kind()) { case SyntaxKind.FieldDeclaration: { var fieldSyntax = (FieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(fieldSyntax.Declaration.Variables.First().Identifier)); } bool modifierErrors; var modifiers = SourceMemberFieldSymbol.MakeModifiers(this, fieldSyntax.Declaration.Variables[0].Identifier, fieldSyntax.Modifiers, diagnostics, out modifierErrors); foreach (var variable in fieldSyntax.Declaration.Variables) { var fieldSymbol = (modifiers & DeclarationModifiers.Fixed) == 0 ? new SourceMemberFieldSymbolFromDeclarator(this, variable, modifiers, modifierErrors, diagnostics) : new SourceFixedFieldSymbol(this, variable, modifiers, modifierErrors, diagnostics); builder.NonTypeMembers.Add(fieldSymbol); // All fields are included in the nullable context for constructors and initializers, even fields without // initializers, to ensure warnings are reported for uninitialized non-nullable fields in NullableWalker. builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: fieldSymbol.IsStatic, compilation, variable); if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, variable, this, DeclarationModifiers.Private | (modifiers & DeclarationModifiers.Static), fieldSymbol); } if (variable.Initializer != null) { if (fieldSymbol.IsStatic) { AddInitializer(ref staticInitializers, fieldSymbol, variable.Initializer); } else { AddInitializer(ref instanceInitializers, fieldSymbol, variable.Initializer); } } } } break; case SyntaxKind.MethodDeclaration: { var methodSyntax = (MethodDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(methodSyntax.Identifier)); } var method = SourceOrdinaryMethodSymbol.CreateMethodSymbol(this, bodyBinder, methodSyntax, compilation.IsNullableAnalysisEnabledIn(methodSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.ConstructorDeclaration: { var constructorSyntax = (ConstructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(constructorSyntax.Identifier)); } bool isNullableEnabled = compilation.IsNullableAnalysisEnabledIn(constructorSyntax); var constructor = SourceConstructorSymbol.CreateConstructorSymbol(this, constructorSyntax, isNullableEnabled, diagnostics); builder.NonTypeMembers.Add(constructor); if (constructorSyntax.Initializer?.Kind() != SyntaxKind.ThisConstructorInitializer) { builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: constructor.IsStatic, isNullableEnabled); } } break; case SyntaxKind.DestructorDeclaration: { var destructorSyntax = (DestructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(destructorSyntax.Identifier)); } // CONSIDER: if this doesn't (directly or indirectly) override object.Finalize, the // runtime won't consider it a finalizer and it will not be marked as a destructor // when it is loaded from metadata. Perhaps we should just treat it as an Ordinary // method in such cases? var destructor = new SourceDestructorSymbol(this, destructorSyntax, compilation.IsNullableAnalysisEnabledIn(destructorSyntax), diagnostics); builder.NonTypeMembers.Add(destructor); } break; case SyntaxKind.PropertyDeclaration: { var propertySyntax = (PropertyDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(propertySyntax.Identifier)); } var property = SourcePropertySymbol.Create(this, bodyBinder, propertySyntax, diagnostics); builder.NonTypeMembers.Add(property); AddAccessorIfAvailable(builder.NonTypeMembers, property.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, property.SetMethod); FieldSymbol backingField = property.BackingField; // TODO: can we leave this out of the member list? // From the 10/12/11 design notes: // In addition, we will change autoproperties to behavior in // a similar manner and make the autoproperty fields private. if ((object)backingField != null) { builder.NonTypeMembers.Add(backingField); builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: backingField.IsStatic, compilation, propertySyntax); var initializer = propertySyntax.Initializer; if (initializer != null) { if (IsScriptClass) { // also gather expression-declared variables from the initializer ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, initializer, this, DeclarationModifiers.Private | (property.IsStatic ? DeclarationModifiers.Static : 0), backingField); } if (property.IsStatic) { AddInitializer(ref staticInitializers, backingField, initializer); } else { AddInitializer(ref instanceInitializers, backingField, initializer); } } } } break; case SyntaxKind.EventFieldDeclaration: { var eventFieldSyntax = (EventFieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add( ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventFieldSyntax.Declaration.Variables.First().Identifier)); } foreach (VariableDeclaratorSyntax declarator in eventFieldSyntax.Declaration.Variables) { SourceFieldLikeEventSymbol @event = new SourceFieldLikeEventSymbol(this, bodyBinder, eventFieldSyntax.Modifiers, declarator, diagnostics); builder.NonTypeMembers.Add(@event); FieldSymbol? associatedField = @event.AssociatedField; if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, declarator, this, DeclarationModifiers.Private | (@event.IsStatic ? DeclarationModifiers.Static : 0), associatedField); } if ((object?)associatedField != null) { // NOTE: specifically don't add the associated field to the members list // (regard it as an implementation detail). builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: associatedField.IsStatic, compilation, declarator); if (declarator.Initializer != null) { if (associatedField.IsStatic) { AddInitializer(ref staticInitializers, associatedField, declarator.Initializer); } else { AddInitializer(ref instanceInitializers, associatedField, declarator.Initializer); } } } Debug.Assert((object)@event.AddMethod != null); Debug.Assert((object)@event.RemoveMethod != null); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); } } break; case SyntaxKind.EventDeclaration: { var eventSyntax = (EventDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventSyntax.Identifier)); } var @event = new SourceCustomEventSymbol(this, bodyBinder, eventSyntax, diagnostics); builder.NonTypeMembers.Add(@event); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); Debug.Assert(@event.AssociatedField is null); } break; case SyntaxKind.IndexerDeclaration: { var indexerSyntax = (IndexerDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(indexerSyntax.ThisKeyword)); } var indexer = SourcePropertySymbol.Create(this, bodyBinder, indexerSyntax, diagnostics); builder.HaveIndexers = true; builder.NonTypeMembers.Add(indexer); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.SetMethod); } break; case SyntaxKind.ConversionOperatorDeclaration: { var conversionOperatorSyntax = (ConversionOperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(conversionOperatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedConversionSymbol.CreateUserDefinedConversionSymbol( this, bodyBinder, conversionOperatorSyntax, compilation.IsNullableAnalysisEnabledIn(conversionOperatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.OperatorDeclaration: { var operatorSyntax = (OperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(operatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedOperatorSymbol.CreateUserDefinedOperatorSymbol( this, bodyBinder, operatorSyntax, compilation.IsNullableAnalysisEnabledIn(operatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.GlobalStatement: { var globalStatement = ((GlobalStatementSyntax)m).Statement; if (IsScriptClass) { var innerStatement = globalStatement; // drill into any LabeledStatements while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } switch (innerStatement.Kind()) { case SyntaxKind.LocalDeclarationStatement: // We shouldn't reach this place, but field declarations preceded with a label end up here. // This is tracked by https://github.com/dotnet/roslyn/issues/13712. Let's do our best for now. var decl = (LocalDeclarationStatementSyntax)innerStatement; foreach (var vdecl in decl.Declaration.Variables) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, vdecl, this, DeclarationModifiers.Private, containingFieldOpt: null); } break; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, innerStatement, this, DeclarationModifiers.Private, containingFieldOpt: null); break; default: // no other statement introduces variables into the enclosing scope break; } AddInitializer(ref instanceInitializers, null, globalStatement); } else if (reportMisplacedGlobalCode && !SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)m)) { diagnostics.Add(ErrorCode.ERR_GlobalStatement, new SourceLocation(globalStatement)); } } break; default: Debug.Assert( SyntaxFacts.IsTypeDeclaration(m.Kind()) || m.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration or SyntaxKind.IncompleteMember); break; } } AddInitializers(builder.InstanceInitializers, instanceInitializers); AddInitializers(builder.StaticInitializers, staticInitializers); } private void AddAccessorIfAvailable(ArrayBuilder<Symbol> symbols, MethodSymbol? accessorOpt) { if (!(accessorOpt is null)) { symbols.Add(accessorOpt); } } internal override byte? GetLocalNullableContextValue() { byte? value; if (!_flags.TryGetNullableContext(out value)) { value = ComputeNullableContextValue(); _flags.SetNullableContext(value); } return value; } private byte? ComputeNullableContextValue() { var compilation = DeclaringCompilation; if (!compilation.ShouldEmitNullableAttributes(this)) { return null; } var builder = new MostCommonNullableValueBuilder(); var baseType = BaseTypeNoUseSiteDiagnostics; if (baseType is object) { builder.AddValue(TypeWithAnnotations.Create(baseType)); } foreach (var @interface in GetInterfacesToEmit()) { builder.AddValue(TypeWithAnnotations.Create(@interface)); } foreach (var typeParameter in TypeParameters) { typeParameter.GetCommonNullableValues(compilation, ref builder); } foreach (var member in GetMembersUnordered()) { member.GetCommonNullableValues(compilation, ref builder); } // Not including lambdas or local functions. return builder.MostCommonValue; } /// <summary> /// Returns true if the overall nullable context is enabled for constructors and initializers. /// </summary> /// <param name="useStatic">Consider static constructor and fields rather than instance constructors and fields.</param> internal bool IsNullableEnabledForConstructorsAndInitializers(bool useStatic) { var membersAndInitializers = GetMembersAndInitializers(); return useStatic ? membersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields : membersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = DeclaringCompilation; NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics; if (baseType is object) { if (baseType.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(baseType, customModifiersCount: 0)); } if (baseType.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, baseType)); } if (baseType.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(baseType)); } } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out byte nullableContextValue)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue)); } if (baseType is object) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, nullableContextValue, TypeWithAnnotations.Create(baseType))); } } } #endregion #region Extension Methods internal bool ContainsExtensionMethods { get { if (!_lazyContainsExtensionMethods.HasValue()) { bool containsExtensionMethods = ((this.IsStatic && !this.IsGenericType) || this.IsScriptClass) && this.declaration.ContainsExtensionMethods; _lazyContainsExtensionMethods = containsExtensionMethods.ToThreeState(); } return _lazyContainsExtensionMethods.Value(); } } internal bool AnyMemberHasAttributes { get { if (!_lazyAnyMemberHasAttributes.HasValue()) { bool anyMemberHasAttributes = this.declaration.AnyMemberHasAttributes; _lazyAnyMemberHasAttributes = anyMemberHasAttributes.ToThreeState(); } return _lazyAnyMemberHasAttributes.Value(); } } public override bool MightContainExtensionMethods { get { return this.ContainsExtensionMethods; } } #endregion public sealed override NamedTypeSymbol ConstructedFrom { get { return this; } } internal sealed override bool HasFieldInitializers() => InstanceInitializers.Length > 0; internal class SynthesizedExplicitImplementations { public static readonly SynthesizedExplicitImplementations Empty = new SynthesizedExplicitImplementations(ImmutableArray<SynthesizedExplicitImplementationForwardingMethod>.Empty, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)>.Empty); public readonly ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> ForwardingMethods; public readonly ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> MethodImpls; private SynthesizedExplicitImplementations( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { ForwardingMethods = forwardingMethods.NullToEmpty(); MethodImpls = methodImpls.NullToEmpty(); } internal static SynthesizedExplicitImplementations Create( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { if (forwardingMethods.IsDefaultOrEmpty && methodImpls.IsDefaultOrEmpty) { return Empty; } return new SynthesizedExplicitImplementations(forwardingMethods, methodImpls); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a named type symbol whose members are declared in source. /// </summary> internal abstract partial class SourceMemberContainerTypeSymbol : NamedTypeSymbol { // The flags type is used to compact many different bits of information efficiently. private struct Flags { // We current pack everything into one 32-bit int; layout is given below. // // | |vvv|zzzz|f|d|yy|wwwwww| // // w = special type. 6 bits. // y = IsManagedType. 2 bits. // d = FieldDefinitionsNoted. 1 bit // f = FlattenedMembersIsSorted. 1 bit. // z = TypeKind. 4 bits. // v = NullableContext. 3 bits. private int _flags; private const int SpecialTypeOffset = 0; private const int SpecialTypeSize = 6; private const int ManagedKindOffset = SpecialTypeOffset + SpecialTypeSize; private const int ManagedKindSize = 2; private const int FieldDefinitionsNotedOffset = ManagedKindOffset + ManagedKindSize; private const int FieldDefinitionsNotedSize = 1; private const int FlattenedMembersIsSortedOffset = FieldDefinitionsNotedOffset + FieldDefinitionsNotedSize; private const int FlattenedMembersIsSortedSize = 1; private const int TypeKindOffset = FlattenedMembersIsSortedOffset + FlattenedMembersIsSortedSize; private const int TypeKindSize = 4; private const int NullableContextOffset = TypeKindOffset + TypeKindSize; private const int NullableContextSize = 3; private const int SpecialTypeMask = (1 << SpecialTypeSize) - 1; private const int ManagedKindMask = (1 << ManagedKindSize) - 1; private const int TypeKindMask = (1 << TypeKindSize) - 1; private const int NullableContextMask = (1 << NullableContextSize) - 1; private const int FieldDefinitionsNotedBit = 1 << FieldDefinitionsNotedOffset; private const int FlattenedMembersIsSortedBit = 1 << FlattenedMembersIsSortedOffset; public SpecialType SpecialType { get { return (SpecialType)((_flags >> SpecialTypeOffset) & SpecialTypeMask); } } public ManagedKind ManagedKind { get { return (ManagedKind)((_flags >> ManagedKindOffset) & ManagedKindMask); } } public bool FieldDefinitionsNoted { get { return (_flags & FieldDefinitionsNotedBit) != 0; } } // True if "lazyMembersFlattened" is sorted. public bool FlattenedMembersIsSorted { get { return (_flags & FlattenedMembersIsSortedBit) != 0; } } public TypeKind TypeKind { get { return (TypeKind)((_flags >> TypeKindOffset) & TypeKindMask); } } #if DEBUG static Flags() { // Verify masks are sufficient for values. Debug.Assert(EnumUtilities.ContainsAllValues<SpecialType>(SpecialTypeMask)); Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask)); } #endif public Flags(SpecialType specialType, TypeKind typeKind) { int specialTypeInt = ((int)specialType & SpecialTypeMask) << SpecialTypeOffset; int typeKindInt = ((int)typeKind & TypeKindMask) << TypeKindOffset; _flags = specialTypeInt | typeKindInt; } public void SetFieldDefinitionsNoted() { ThreadSafeFlagOperations.Set(ref _flags, FieldDefinitionsNotedBit); } public void SetFlattenedMembersIsSorted() { ThreadSafeFlagOperations.Set(ref _flags, (FlattenedMembersIsSortedBit)); } private static bool BitsAreUnsetOrSame(int bits, int mask) { return (bits & mask) == 0 || (bits & mask) == mask; } public void SetManagedKind(ManagedKind managedKind) { int bitsToSet = ((int)managedKind & ManagedKindMask) << ManagedKindOffset; Debug.Assert(BitsAreUnsetOrSame(_flags, bitsToSet)); ThreadSafeFlagOperations.Set(ref _flags, bitsToSet); } public bool TryGetNullableContext(out byte? value) { return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value); } public bool SetNullableContext(byte? value) { return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset)); } } private static readonly ObjectPool<PooledDictionary<Symbol, Symbol>> s_duplicateRecordMemberSignatureDictionary = PooledDictionary<Symbol, Symbol>.CreatePool(MemberSignatureComparer.RecordAPISignatureComparer); protected SymbolCompletionState state; private Flags _flags; private ImmutableArray<DiagnosticInfo> _managedKindUseSiteDiagnostics; private ImmutableArray<AssemblySymbol> _managedKindUseSiteDependencies; private readonly DeclarationModifiers _declModifiers; private readonly NamespaceOrTypeSymbol _containingSymbol; protected readonly MergedTypeDeclaration declaration; // The entry point symbol (resulting from top-level statements) is needed to construct non-type members because // it contributes to their binders, so we have to compute it first. // The value changes from "uninitialized" to "real value". The transition from "uninitialized" can only happen once. private SimpleProgramEntryPointInfo? _lazySimpleProgramEntryPoint = SimpleProgramEntryPointInfo.UninitializedSentinel; // To compute explicitly declared members, binding must be limited (to avoid race conditions where binder cache captures symbols that aren't part of the final set) // The value changes from "uninitialized" to "real value" to null. The transition from "uninitialized" can only happen once. private DeclaredMembersAndInitializers? _lazyDeclaredMembersAndInitializers = DeclaredMembersAndInitializers.UninitializedSentinel; private MembersAndInitializers? _lazyMembersAndInitializers; private Dictionary<string, ImmutableArray<Symbol>>? _lazyMembersDictionary; private Dictionary<string, ImmutableArray<Symbol>>? _lazyEarlyAttributeDecodingMembersDictionary; private static readonly Dictionary<string, ImmutableArray<NamedTypeSymbol>> s_emptyTypeMembers = new Dictionary<string, ImmutableArray<NamedTypeSymbol>>(EmptyComparer.Instance); private Dictionary<string, ImmutableArray<NamedTypeSymbol>>? _lazyTypeMembers; private ImmutableArray<Symbol> _lazyMembersFlattened; private SynthesizedExplicitImplementations? _lazySynthesizedExplicitImplementations; private int _lazyKnownCircularStruct; private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized; private ThreeState _lazyContainsExtensionMethods; private ThreeState _lazyAnyMemberHasAttributes; #region Construction internal SourceMemberContainerTypeSymbol( NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics, TupleExtraData? tupleData = null) : base(tupleData) { // If we're dealing with a simple program, then we must be in the global namespace Debug.Assert(containingSymbol is NamespaceSymbol { IsGlobalNamespace: true } || !declaration.Declarations.Any(d => d.IsSimpleProgram)); _containingSymbol = containingSymbol; this.declaration = declaration; TypeKind typeKind = declaration.Kind.ToTypeKind(); var modifiers = MakeModifiers(typeKind, diagnostics); foreach (var singleDeclaration in declaration.Declarations) { diagnostics.AddRange(singleDeclaration.Diagnostics); } int access = (int)(modifiers & DeclarationModifiers.AccessibilityMask); if ((access & (access - 1)) != 0) { // more than one access modifier if ((modifiers & DeclarationModifiers.Partial) != 0) diagnostics.Add(ErrorCode.ERR_PartialModifierConflict, Locations[0], this); access = access & ~(access - 1); // narrow down to one access modifier modifiers &= ~DeclarationModifiers.AccessibilityMask; // remove them all modifiers |= (DeclarationModifiers)access; // except the one } _declModifiers = modifiers; var specialType = access == (int)DeclarationModifiers.Public ? MakeSpecialType() : SpecialType.None; _flags = new Flags(specialType, typeKind); var containingType = this.ContainingType; if (containingType?.IsSealed == true && this.DeclaredAccessibility.HasProtected()) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), Locations[0], this); } state.NotePartComplete(CompletionPart.TypeArguments); // type arguments need not be computed separately } private SpecialType MakeSpecialType() { // check if this is one of the COR library types if (ContainingSymbol.Kind == SymbolKind.Namespace && ContainingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes) { //for a namespace, the emitted name is a dot-separated list of containing namespaces var emittedName = ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName); return SpecialTypes.GetTypeFromMetadataName(emittedName); } else { return SpecialType.None; } } private DeclarationModifiers MakeModifiers(TypeKind typeKind, BindingDiagnosticBag diagnostics) { Symbol containingSymbol = this.ContainingSymbol; DeclarationModifiers defaultAccess; var allowedModifiers = DeclarationModifiers.AccessibilityMask; if (containingSymbol.Kind == SymbolKind.Namespace) { defaultAccess = DeclarationModifiers.Internal; } else { allowedModifiers |= DeclarationModifiers.New; if (((NamedTypeSymbol)containingSymbol).IsInterface) { defaultAccess = DeclarationModifiers.Public; } else { defaultAccess = DeclarationModifiers.Private; } } switch (typeKind) { case TypeKind.Class: case TypeKind.Submission: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Unsafe; if (!this.IsRecord) { allowedModifiers |= DeclarationModifiers.Static; } break; case TypeKind.Struct: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Unsafe; if (!this.IsRecordStruct) { allowedModifiers |= DeclarationModifiers.Ref; } break; case TypeKind.Interface: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; break; case TypeKind.Delegate: allowedModifiers |= DeclarationModifiers.Unsafe; break; } bool modifierErrors; var mods = MakeAndCheckTypeModifiers( defaultAccess, allowedModifiers, diagnostics, out modifierErrors); this.CheckUnsafeModifier(mods, diagnostics); if (!modifierErrors && (mods & DeclarationModifiers.Abstract) != 0 && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) != 0) { diagnostics.Add(ErrorCode.ERR_AbstractSealedStatic, Locations[0], this); } if (!modifierErrors && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) { diagnostics.Add(ErrorCode.ERR_SealedStaticClass, Locations[0], this); } switch (typeKind) { case TypeKind.Interface: mods |= DeclarationModifiers.Abstract; break; case TypeKind.Struct: case TypeKind.Enum: mods |= DeclarationModifiers.Sealed; break; case TypeKind.Delegate: mods |= DeclarationModifiers.Sealed; break; } return mods; } private DeclarationModifiers MakeAndCheckTypeModifiers( DeclarationModifiers defaultAccess, DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics, out bool modifierErrors) { modifierErrors = false; var result = DeclarationModifiers.Unset; var partCount = declaration.Declarations.Length; var missingPartial = false; for (var i = 0; i < partCount; i++) { var decl = declaration.Declarations[i]; var mods = decl.Modifiers; if (partCount > 1 && (mods & DeclarationModifiers.Partial) == 0) { missingPartial = true; } if (!modifierErrors) { mods = ModifierUtils.CheckModifiers( mods, allowedModifiers, declaration.Declarations[i].NameLocation, diagnostics, modifierTokens: null, modifierErrors: out modifierErrors); // It is an error for the same modifier to appear multiple times. if (!modifierErrors) { var info = ModifierUtils.CheckAccessibility(mods, this, isExplicitInterfaceImplementation: false); if (info != null) { diagnostics.Add(info, this.Locations[0]); modifierErrors = true; } } } if (result == DeclarationModifiers.Unset) { result = mods; } else { result |= mods; } } if ((result & DeclarationModifiers.AccessibilityMask) == 0) { result |= defaultAccess; } if (missingPartial) { if ((result & DeclarationModifiers.Partial) == 0) { // duplicate definitions switch (this.ContainingSymbol.Kind) { case SymbolKind.Namespace: for (var i = 1; i < partCount; i++) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, declaration.Declarations[i].NameLocation, this.Name, this.ContainingSymbol); modifierErrors = true; } break; case SymbolKind.NamedType: for (var i = 1; i < partCount; i++) { if (ContainingType!.Locations.Length == 1 || ContainingType.IsPartial()) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, declaration.Declarations[i].NameLocation, this.ContainingSymbol, this.Name); modifierErrors = true; } break; } } else { for (var i = 0; i < partCount; i++) { var singleDeclaration = declaration.Declarations[i]; var mods = singleDeclaration.Modifiers; if ((mods & DeclarationModifiers.Partial) == 0) { diagnostics.Add(ErrorCode.ERR_MissingPartial, singleDeclaration.NameLocation, this.Name); modifierErrors = true; } } } } if (this.Name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword)) { foreach (var syntaxRef in SyntaxReferences) { SyntaxToken? identifier = syntaxRef.GetSyntax() switch { BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier, DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier, _ => null }; ReportTypeNamedRecord(identifier?.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, identifier?.GetLocation() ?? Location.None); } } return result; } internal static void ReportTypeNamedRecord(string? name, CSharpCompilation compilation, DiagnosticBag? diagnostics, Location location) { if (diagnostics is object && name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword) && compilation.LanguageVersion >= MessageID.IDS_FeatureRecords.RequiredVersion()) { diagnostics.Add(ErrorCode.WRN_RecordNamedDisallowed, location, name); } } #endregion #region Completion internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } protected abstract void CheckBase(BindingDiagnosticBag diagnostics); protected abstract void CheckInterfaces(BindingDiagnosticBag diagnostics); internal override void ForceComplete(SourceLocation? locationOpt, CancellationToken cancellationToken) { while (true) { // NOTE: cases that depend on GetMembers[ByName] should call RequireCompletionPartMembers. cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.StartBaseType: case CompletionPart.FinishBaseType: if (state.NotePartComplete(CompletionPart.StartBaseType)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckBase(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishBaseType); diagnostics.Free(); } break; case CompletionPart.StartInterfaces: case CompletionPart.FinishInterfaces: if (state.NotePartComplete(CompletionPart.StartInterfaces)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckInterfaces(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishInterfaces); diagnostics.Free(); } break; case CompletionPart.EnumUnderlyingType: var discarded = this.EnumUnderlyingType; break; case CompletionPart.TypeArguments: { var tmp = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; // force type arguments } break; case CompletionPart.TypeParameters: // force type parameters foreach (var typeParameter in this.TypeParameters) { typeParameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.TypeParameters); break; case CompletionPart.Members: this.GetMembersByName(); break; case CompletionPart.TypeMembers: this.GetTypeMembersUnordered(); break; case CompletionPart.SynthesizedExplicitImplementations: this.GetSynthesizedExplicitImplementations(cancellationToken); //force interface and base class errors to be checked break; case CompletionPart.StartMemberChecks: case CompletionPart.FinishMemberChecks: if (state.NotePartComplete(CompletionPart.StartMemberChecks)) { var diagnostics = BindingDiagnosticBag.GetInstance(); AfterMembersChecks(diagnostics); AddDeclarationDiagnostics(diagnostics); // We may produce a SymbolDeclaredEvent for the enclosing type before events for its contained members DeclaringCompilation.SymbolDeclaredEvent(this); var thisThreadCompleted = state.NotePartComplete(CompletionPart.FinishMemberChecks); Debug.Assert(thisThreadCompleted); diagnostics.Free(); } break; case CompletionPart.MembersCompleted: { ImmutableArray<Symbol> members = this.GetMembersUnordered(); bool allCompleted = true; if (locationOpt == null) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); member.ForceComplete(locationOpt, cancellationToken); } } else { foreach (var member in members) { ForceCompleteMemberByLocation(locationOpt, member, cancellationToken); allCompleted = allCompleted && member.HasComplete(CompletionPart.All); } } if (!allCompleted) { // We did not complete all members so we won't have enough information for // the PointedAtManagedTypeChecks, so just kick out now. var allParts = CompletionPart.NamedTypeSymbolWithLocationAll; state.SpinWaitComplete(allParts, cancellationToken); return; } EnsureFieldDefinitionsNoted(); // We've completed all members, so we're ready for the PointedAtManagedTypeChecks; // proceed to the next iteration. state.NotePartComplete(CompletionPart.MembersCompleted); break; } case CompletionPart.None: return; default: // This assert will trigger if we forgot to handle any of the completion parts Debug.Assert((incompletePart & CompletionPart.NamedTypeSymbolAll) == 0); // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.NamedTypeSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } throw ExceptionUtilities.Unreachable; } internal void EnsureFieldDefinitionsNoted() { if (_flags.FieldDefinitionsNoted) { return; } NoteFieldDefinitions(); } private void NoteFieldDefinitions() { // we must note all fields once therefore we need to lock var membersAndInitializers = this.GetMembersAndInitializers(); lock (membersAndInitializers) { if (!_flags.FieldDefinitionsNoted) { var assembly = (SourceAssemblySymbol)ContainingAssembly; Accessibility containerEffectiveAccessibility = EffectiveAccessibility(); foreach (var member in membersAndInitializers.NonTypeMembers) { FieldSymbol field; if (!member.IsFieldOrFieldLikeEvent(out field) || field.IsConst || field.IsFixedSizeBuffer) { continue; } Accessibility fieldDeclaredAccessibility = field.DeclaredAccessibility; if (fieldDeclaredAccessibility == Accessibility.Private) { // mark private fields as tentatively unassigned and unread unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: true); } else if (containerEffectiveAccessibility == Accessibility.Private) { // mark effectively private fields as tentatively unassigned unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: false); } else if (fieldDeclaredAccessibility == Accessibility.Internal || containerEffectiveAccessibility == Accessibility.Internal) { // mark effectively internal fields as tentatively unassigned unless we discover otherwise. // NOTE: These fields will be reported as unassigned only if internals are not visible from this assembly. // See property SourceAssemblySymbol.UnusedFieldWarnings. assembly.NoteFieldDefinition(field, isInternal: true, isUnread: false); } } _flags.SetFieldDefinitionsNoted(); } } } #endregion #region Containers public sealed override NamedTypeSymbol? ContainingType { get { return _containingSymbol as NamedTypeSymbol; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } #endregion #region Flags Encoded Properties public override SpecialType SpecialType { get { return _flags.SpecialType; } } public override TypeKind TypeKind { get { return _flags.TypeKind; } } internal MergedTypeDeclaration MergedDeclaration { get { return this.declaration; } } internal sealed override bool IsInterface { get { // TypeKind is computed eagerly, so this is cheap. return this.TypeKind == TypeKind.Interface; } } internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var managedKind = _flags.ManagedKind; if (managedKind == ManagedKind.Unknown) { var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(ContainingAssembly); managedKind = base.GetManagedKind(ref managedKindUseSiteInfo); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDiagnostics, managedKindUseSiteInfo.Diagnostics?.ToImmutableArray() ?? ImmutableArray<DiagnosticInfo>.Empty); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDependencies, managedKindUseSiteInfo.Dependencies?.ToImmutableArray() ?? ImmutableArray<AssemblySymbol>.Empty); _flags.SetManagedKind(managedKind); } if (useSiteInfo.AccumulatesDiagnostics) { ImmutableArray<DiagnosticInfo> useSiteDiagnostics = _managedKindUseSiteDiagnostics; // Ensure we have the latest value from the field useSiteDiagnostics = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDiagnostics, useSiteDiagnostics, useSiteDiagnostics); Debug.Assert(!useSiteDiagnostics.IsDefault); useSiteInfo.AddDiagnostics(useSiteDiagnostics); } if (useSiteInfo.AccumulatesDependencies) { ImmutableArray<AssemblySymbol> useSiteDependencies = _managedKindUseSiteDependencies; // Ensure we have the latest value from the field useSiteDependencies = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDependencies, useSiteDependencies, useSiteDependencies); Debug.Assert(!useSiteDependencies.IsDefault); useSiteInfo.AddDependencies(useSiteDependencies); } return managedKind; } public override bool IsStatic => HasFlag(DeclarationModifiers.Static); public sealed override bool IsRefLikeType => HasFlag(DeclarationModifiers.Ref); public override bool IsReadOnly => HasFlag(DeclarationModifiers.ReadOnly); public override bool IsSealed => HasFlag(DeclarationModifiers.Sealed); public override bool IsAbstract => HasFlag(DeclarationModifiers.Abstract); internal bool IsPartial => HasFlag(DeclarationModifiers.Partial); internal bool IsNew => HasFlag(DeclarationModifiers.New); [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HasFlag(DeclarationModifiers flag) => (_declModifiers & flag) != 0; public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(_declModifiers); } } /// <summary> /// Compute the "effective accessibility" of the current class for the purpose of warnings about unused fields. /// </summary> private Accessibility EffectiveAccessibility() { var result = DeclaredAccessibility; if (result == Accessibility.Private) return Accessibility.Private; for (Symbol? container = this.ContainingType; !(container is null); container = container.ContainingType) { switch (container.DeclaredAccessibility) { case Accessibility.Private: return Accessibility.Private; case Accessibility.Internal: result = Accessibility.Internal; continue; } } return result; } #endregion #region Syntax public override bool IsScriptClass { get { var kind = this.declaration.Declarations[0].Kind; return kind == DeclarationKind.Script || kind == DeclarationKind.Submission; } } public override bool IsImplicitClass { get { return this.declaration.Declarations[0].Kind == DeclarationKind.ImplicitClass; } } internal override bool IsRecord { get { return this.declaration.Declarations[0].Kind == DeclarationKind.Record; } } internal override bool IsRecordStruct { get { return this.declaration.Declarations[0].Kind == DeclarationKind.RecordStruct; } } public override bool IsImplicitlyDeclared { get { return IsImplicitClass || IsScriptClass; } } public override int Arity { get { return declaration.Arity; } } public override string Name { get { return declaration.Name; } } internal override bool MangleName { get { return Arity > 0; } } internal override LexicalSortKey GetLexicalSortKey() { if (!_lazyLexicalSortKey.IsInitialized) { _lazyLexicalSortKey.SetFrom(declaration.GetLexicalSortKey(this.DeclaringCompilation)); } return _lazyLexicalSortKey; } public override ImmutableArray<Location> Locations { get { return declaration.NameLocations.Cast<SourceLocation, Location>(); } } public ImmutableArray<SyntaxReference> SyntaxReferences { get { return this.declaration.SyntaxReferences; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return SyntaxReferences; } } // This method behaves the same was as the base class, but avoids allocations associated with DeclaringSyntaxReferences internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken) { var declarations = declaration.Declarations; if (IsImplicitlyDeclared && declarations.IsEmpty) { return ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken); } foreach (var declaration in declarations) { cancellationToken.ThrowIfCancellationRequested(); var syntaxRef = declaration.SyntaxReference; if (syntaxRef.SyntaxTree == tree && (!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value))) { return true; } } return false; } #endregion #region Members /// <summary> /// Encapsulates information about the non-type members of a (i.e. this) type. /// 1) For non-initializers, symbols are created and stored in a list. /// 2) For fields and properties/indexers, the symbols are stored in (1) and their initializers are /// stored with other initialized fields and properties from the same syntax tree with /// the same static-ness. /// </summary> protected sealed class MembersAndInitializers { internal readonly ImmutableArray<Symbol> NonTypeMembers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; internal readonly bool HaveIndexers; internal readonly bool IsNullableEnabledForInstanceConstructorsAndFields; internal readonly bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields) { Debug.Assert(!nonTypeMembers.IsDefault); Debug.Assert(!staticInitializers.IsDefault); Debug.Assert(staticInitializers.All(g => !g.IsDefault)); Debug.Assert(!instanceInitializers.IsDefault); Debug.Assert(instanceInitializers.All(g => !g.IsDefault)); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(haveIndexers == nonTypeMembers.Any(s => s.IsIndexer())); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers { get { return GetMembersAndInitializers().StaticInitializers; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers { get { return GetMembersAndInitializers().InstanceInitializers; } } internal int CalculateSyntaxOffsetInSynthesizedConstructor(int position, SyntaxTree tree, bool isStatic) { if (IsScriptClass && !isStatic) { int aggregateLength = 0; foreach (var declaration in this.declaration.Declarations) { var syntaxRef = declaration.SyntaxReference; if (tree == syntaxRef.SyntaxTree) { return aggregateLength + position; } aggregateLength += syntaxRef.Span.Length; } throw ExceptionUtilities.Unreachable; } int syntaxOffset; if (TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, isStatic, ctorInitializerLength: 0, syntaxOffset: out syntaxOffset)) { return syntaxOffset; } if (declaration.Declarations.Length >= 1 && position == declaration.Declarations[0].Location.SourceSpan.Start) { // With dynamic analysis instrumentation, the introducing declaration of a type can provide // the syntax associated with both the analysis payload local of a synthesized constructor // and with the constructor itself. If the synthesized constructor includes an initializer with a lambda, // that lambda needs a closure that captures the analysis payload of the constructor, // and the offset of the syntax for the local within the constructor is by definition zero. return 0; } // an implicit constructor has no body and no initializer, so the variable has to be declared in a member initializer throw ExceptionUtilities.Unreachable; } /// <summary> /// Calculates a syntax offset of a syntax position that is contained in a property or field initializer (if it is in fact contained in one). /// </summary> internal bool TryCalculateSyntaxOffsetOfPositionInInitializer(int position, SyntaxTree tree, bool isStatic, int ctorInitializerLength, out int syntaxOffset) { Debug.Assert(ctorInitializerLength >= 0); var membersAndInitializers = GetMembersAndInitializers(); var allInitializers = isStatic ? membersAndInitializers.StaticInitializers : membersAndInitializers.InstanceInitializers; if (!findInitializer(allInitializers, position, tree, out FieldOrPropertyInitializer initializer, out int precedingLength)) { syntaxOffset = 0; return false; } // |<-----------distanceFromCtorBody----------->| // [ initializer 0 ][ initializer 1 ][ initializer 2 ][ctor initializer][ctor body] // |<--preceding init len-->| ^ // position int initializersLength = getInitializersLength(allInitializers); int distanceFromInitializerStart = position - initializer.Syntax.Span.Start; int distanceFromCtorBody = initializersLength + ctorInitializerLength - (precedingLength + distanceFromInitializerStart); Debug.Assert(distanceFromCtorBody > 0); // syntax offset 0 is at the start of the ctor body: syntaxOffset = -distanceFromCtorBody; return true; static bool findInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, int position, SyntaxTree tree, out FieldOrPropertyInitializer found, out int precedingLength) { precedingLength = 0; foreach (var group in initializers) { if (!group.IsEmpty && group[0].Syntax.SyntaxTree == tree && position < group.Last().Syntax.Span.End) { // Found group of interest var initializerIndex = IndexOfInitializerContainingPosition(group, position); if (initializerIndex < 0) { break; } precedingLength += getPrecedingInitializersLength(group, initializerIndex); found = group[initializerIndex]; return true; } precedingLength += getGroupLength(group); } found = default; return false; } static int getGroupLength(ImmutableArray<FieldOrPropertyInitializer> initializers) { int length = 0; foreach (var initializer in initializers) { length += getInitializerLength(initializer); } return length; } static int getPrecedingInitializersLength(ImmutableArray<FieldOrPropertyInitializer> initializers, int index) { int length = 0; for (var i = 0; i < index; i++) { length += getInitializerLength(initializers[i]); } return length; } static int getInitializersLength(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { int length = 0; foreach (var group in initializers) { length += getGroupLength(group); } return length; } static int getInitializerLength(FieldOrPropertyInitializer initializer) { // A constant field of type decimal needs a field initializer, so // check if it is a metadata constant, not just a constant to exclude // decimals. Other constants do not need field initializers. if (initializer.FieldOpt == null || !initializer.FieldOpt.IsMetadataConstant) { // ignore leading and trailing trivia of the node: return initializer.Syntax.Span.Length; } return 0; } } private static int IndexOfInitializerContainingPosition(ImmutableArray<FieldOrPropertyInitializer> initializers, int position) { // Search for the start of the span (the spans are non-overlapping and sorted) int index = initializers.BinarySearch(position, (initializer, pos) => initializer.Syntax.Span.Start.CompareTo(pos)); // Binary search returns non-negative result if the position is exactly the start of some span. if (index >= 0) { return index; } // Otherwise, ~index is the closest span whose start is greater than the position. // => Check if the preceding initializer span contains the position. int precedingInitializerIndex = ~index - 1; if (precedingInitializerIndex >= 0 && initializers[precedingInitializerIndex].Syntax.Span.Contains(position)) { return precedingInitializerIndex; } return -1; } public override IEnumerable<string> MemberNames { get { return (IsTupleType || IsRecord || IsRecordStruct) ? GetMembers().Select(m => m.Name) : this.declaration.MemberNames; } } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return GetTypeMembersDictionary().Flatten(); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return GetTypeMembersDictionary().Flatten(LexicalOrderSymbolComparer.Instance); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { ImmutableArray<NamedTypeSymbol> members; if (GetTypeMembersDictionary().TryGetValue(name, out members)) { return members; } return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity); } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetTypeMembersDictionary() { if (_lazyTypeMembers == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); if (Interlocked.CompareExchange(ref _lazyTypeMembers, MakeTypeMembers(diagnostics), null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.TypeMembers); } diagnostics.Free(); } return _lazyTypeMembers; } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> MakeTypeMembers(BindingDiagnosticBag diagnostics) { var symbols = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var conflictDict = new Dictionary<(string, int), SourceNamedTypeSymbol>(); try { foreach (var childDeclaration in declaration.Children) { var t = new SourceNamedTypeSymbol(this, childDeclaration, diagnostics); this.CheckMemberNameDistinctFromType(t, diagnostics); var key = (t.Name, t.Arity); SourceNamedTypeSymbol? other; if (conflictDict.TryGetValue(key, out other)) { if (Locations.Length == 1 || IsPartial) { if (t.IsPartial && other.IsPartial) { diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, t.Locations[0], t); } else { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, t.Locations[0], this, t.Name); } } } else { conflictDict.Add(key, t); } symbols.Add(t); } if (IsInterface) { foreach (var t in symbols) { Binder.CheckFeatureAvailability(t.DeclaringSyntaxReferences[0].GetSyntax(), MessageID.IDS_DefaultInterfaceImplementation, diagnostics, t.Locations[0]); } } Debug.Assert(s_emptyTypeMembers.Count == 0); return symbols.Count > 0 ? symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance) : s_emptyTypeMembers; } finally { symbols.Free(); } } private void CheckMemberNameDistinctFromType(Symbol member, BindingDiagnosticBag diagnostics) { switch (this.TypeKind) { case TypeKind.Class: case TypeKind.Struct: if (member.Name == this.Name) { diagnostics.Add(ErrorCode.ERR_MemberNameSameAsType, member.Locations[0], this.Name); } break; case TypeKind.Interface: if (member.IsStatic) { goto case TypeKind.Class; } break; } } internal override ImmutableArray<Symbol> GetMembersUnordered() { var result = _lazyMembersFlattened; if (result.IsDefault) { result = GetMembersByName().Flatten(null); // do not sort. ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersFlattened, result); result = _lazyMembersFlattened; } return result.ConditionallyDeOrder(); } public override ImmutableArray<Symbol> GetMembers() { if (_flags.FlattenedMembersIsSorted) { return _lazyMembersFlattened; } else { var allMembers = this.GetMembersUnordered(); if (allMembers.Length > 1) { // The array isn't sorted. Sort it and remember that we sorted it. allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance); ImmutableInterlocked.InterlockedExchange(ref _lazyMembersFlattened, allMembers); } _flags.SetFlattenedMembersIsSorted(); return allMembers; } } public sealed override ImmutableArray<Symbol> GetMembers(string name) { ImmutableArray<Symbol> members; if (GetMembersByName().TryGetValue(name, out members)) { return members; } return ImmutableArray<Symbol>.Empty; } /// <remarks> /// For source symbols, there can only be a valid clone method if this is a record, which is a /// simple syntax check. This will need to change when we generalize cloning, but it's a good /// heuristic for now. /// </remarks> internal override bool HasPossibleWellKnownCloneMethod() => IsRecord; internal override ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { if (_lazyMembersDictionary != null || declaration.MemberNames.Contains(name) || declaration.Kind is DeclarationKind.Record or DeclarationKind.RecordStruct) { return GetMembers(name); } return ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { if (this.TypeKind == TypeKind.Enum) { // For consistency with Dev10, emit value__ field first. var valueField = ((SourceNamedTypeSymbol)this).EnumValueField; RoslynDebug.Assert((object)valueField != null); yield return valueField; } foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: if (m is TupleErrorFieldSymbol) { break; } yield return (FieldSymbol)m; break; case SymbolKind.Event: FieldSymbol? associatedField = ((EventSymbol)m).AssociatedField; if ((object?)associatedField != null) { yield return associatedField; } break; } } } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return GetEarlyAttributeDecodingMembersDictionary().Flatten(); } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol that have a particular name. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { ImmutableArray<Symbol> result; return GetEarlyAttributeDecodingMembersDictionary().TryGetValue(name, out result) ? result : ImmutableArray<Symbol>.Empty; } private Dictionary<string, ImmutableArray<Symbol>> GetEarlyAttributeDecodingMembersDictionary() { if (_lazyEarlyAttributeDecodingMembersDictionary == null) { if (Volatile.Read(ref _lazyMembersDictionary) is Dictionary<string, ImmutableArray<Symbol>> result) { return result; } var membersAndInitializers = GetMembersAndInitializers(); //NOTE: separately cached // NOTE: members were added in a single pass over the syntax, so they're already // in lexical order. Dictionary<string, ImmutableArray<Symbol>> membersByName; if (!membersAndInitializers.HaveIndexers) { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name); } else { // We can't include indexer symbol yet, because we don't know // what name it will have after attribute binding (because of // IndexerNameAttribute). membersByName = membersAndInitializers.NonTypeMembers. WhereAsArray(s => !s.IsIndexer() && (!s.IsAccessor() || ((MethodSymbol)s).AssociatedSymbol?.IsIndexer() != true)). ToDictionary(s => s.Name); } AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); Interlocked.CompareExchange(ref _lazyEarlyAttributeDecodingMembersDictionary, membersByName, null); } return _lazyEarlyAttributeDecodingMembersDictionary; } // NOTE: this method should do as little work as possible // we often need to get members just to do a lookup. // All additional checks and diagnostics may be not // needed yet or at all. protected MembersAndInitializers GetMembersAndInitializers() { var membersAndInitializers = _lazyMembersAndInitializers; if (membersAndInitializers != null) { return membersAndInitializers; } var diagnostics = BindingDiagnosticBag.GetInstance(); membersAndInitializers = BuildMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyMembersAndInitializers, membersAndInitializers, null); if (alreadyKnown != null) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); _lazyDeclaredMembersAndInitializers = null; return membersAndInitializers!; } /// <summary> /// The purpose of this function is to assert that the <paramref name="member"/> symbol /// is actually among the symbols cached by this type symbol in a way that ensures /// that any consumer of standard APIs to get to type's members is going to get the same /// symbol (same instance) for the member rather than an equivalent, but different instance. /// </summary> [Conditional("DEBUG")] internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false) { if (member is FieldSymbol && forDiagnostics && this.IsTupleType) { // There is a problem with binding types of fields in tuple types. // Skipping verification for them temporarily. return; } if (member is NamedTypeSymbol type) { RoslynDebug.AssertOrFailFast(forDiagnostics); RoslynDebug.AssertOrFailFast(Volatile.Read(ref _lazyTypeMembers)?.Values.Any(types => types.Contains(t => t == (object)type)) == true); return; } else if (member is TypeParameterSymbol || member is SynthesizedMethodBaseSymbol) { RoslynDebug.AssertOrFailFast(forDiagnostics); return; } else if (member is FieldSymbol field && field.AssociatedSymbol is EventSymbol e) { RoslynDebug.AssertOrFailFast(forDiagnostics); // Backing fields for field-like events are not added to the members list. member = e; } var membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } if (membersAndInitializers is null) { if (member is SynthesizedSimpleProgramEntryPointSymbol) { RoslynDebug.AssertOrFailFast(GetSimpleProgramEntryPoints().Contains(m => m == (object)member)); return; } var declared = Volatile.Read(ref _lazyDeclaredMembersAndInitializers); RoslynDebug.AssertOrFailFast(declared != DeclaredMembersAndInitializers.UninitializedSentinel); if (declared is object) { if (declared.NonTypeMembers.Contains(m => m == (object)member) || declared.RecordPrimaryConstructor == (object)member) { return; } } else { // It looks like there was a race and we need to check _lazyMembersAndInitializers again membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); RoslynDebug.AssertOrFailFast(membersAndInitializers is object); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } } } RoslynDebug.AssertOrFailFast(false, "Premature symbol exposure."); static bool isMemberInCompleteMemberList(MembersAndInitializers? membersAndInitializers, Symbol member) { return membersAndInitializers?.NonTypeMembers.Contains(m => m == (object)member) == true; } } protected Dictionary<string, ImmutableArray<Symbol>> GetMembersByName() { if (this.state.HasComplete(CompletionPart.Members)) { return _lazyMembersDictionary!; } return GetMembersByNameSlow(); } private Dictionary<string, ImmutableArray<Symbol>> GetMembersByNameSlow() { if (_lazyMembersDictionary == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); var membersDictionary = MakeAllMembers(diagnostics); if (Interlocked.CompareExchange(ref _lazyMembersDictionary, membersDictionary, null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.Members); } diagnostics.Free(); } state.SpinWaitComplete(CompletionPart.Members, default(CancellationToken)); return _lazyMembersDictionary; } internal override IEnumerable<Symbol> GetInstanceFieldsAndEvents() { var membersAndInitializers = this.GetMembersAndInitializers(); return membersAndInitializers.NonTypeMembers.Where(IsInstanceFieldOrEvent); } protected void AfterMembersChecks(BindingDiagnosticBag diagnostics) { if (IsInterface) { CheckInterfaceMembers(this.GetMembersAndInitializers().NonTypeMembers, diagnostics); } CheckMemberNamesDistinctFromType(diagnostics); CheckMemberNameConflicts(diagnostics); CheckRecordMemberNames(diagnostics); CheckSpecialMemberErrors(diagnostics); CheckTypeParameterNameConflicts(diagnostics); CheckAccessorNameConflicts(diagnostics); bool unused = KnownCircularStruct; CheckSequentialOnPartialType(diagnostics); CheckForProtectedInStaticClass(diagnostics); CheckForUnmatchedOperators(diagnostics); var location = Locations[0]; var compilation = DeclaringCompilation; if (this.IsRefLikeType) { compilation.EnsureIsByRefLikeAttributeExists(diagnostics, location, modifyCompilation: true); } if (this.IsReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } var baseType = BaseTypeNoUseSiteDiagnostics; var interfaces = GetInterfacesToEmit(); // https://github.com/dotnet/roslyn/issues/30080: Report diagnostics for base type and interfaces at more specific locations. if (hasBaseTypeOrInterface(t => t.ContainsNativeInteger())) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true); } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out _)) { compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true); } if (hasBaseTypeOrInterface(t => t.NeedsNullableAttribute())) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true); } } if (interfaces.Any(t => needsTupleElementNamesAttribute(t))) { // Note: we don't need to check base type or directly implemented interfaces (which will be reported during binding) // so the checking of all interfaces here involves some redundancy. Binder.ReportMissingTupleElementNamesAttributesIfNeeded(compilation, location, diagnostics); } bool hasBaseTypeOrInterface(Func<NamedTypeSymbol, bool> predicate) { return ((object)baseType != null && predicate(baseType)) || interfaces.Any(predicate); } static bool needsTupleElementNamesAttribute(TypeSymbol type) { if (type is null) { return false; } var resultType = type.VisitType( predicate: (t, a, b) => !t.TupleElementNames.IsDefaultOrEmpty && !t.IsErrorType(), arg: (object?)null); return resultType is object; } } private void CheckMemberNamesDistinctFromType(BindingDiagnosticBag diagnostics) { foreach (var member in GetMembersAndInitializers().NonTypeMembers) { CheckMemberNameDistinctFromType(member, diagnostics); } } private void CheckRecordMemberNames(BindingDiagnosticBag diagnostics) { if (declaration.Kind != DeclarationKind.Record && declaration.Kind != DeclarationKind.RecordStruct) { return; } foreach (var member in GetMembers("Clone")) { diagnostics.Add(ErrorCode.ERR_CloneDisallowedInRecord, member.Locations[0]); } } private void CheckMemberNameConflicts(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName = GetMembersByName(); // Collisions involving indexers are handled specially. CheckIndexerNameConflicts(diagnostics, membersByName); // key and value will be the same object in these dictionaries. var methodsBySignature = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsMethods = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsConversions = new HashSet<SourceUserDefinedConversionSymbol>(ConversionSignatureComparer.Comparer); // SPEC: The signature of an operator must differ from the signatures of all other // SPEC: operators declared in the same class. // DELIBERATE SPEC VIOLATION: // The specification does not state that a user-defined conversion reserves the names // op_Implicit or op_Explicit, but nevertheless the native compiler does so; an attempt // to define a field or a conflicting method with the metadata name of a user-defined // conversion is an error. We preserve this reasonable behavior. // // Similarly, we treat "public static C operator +(C, C)" as colliding with // "public static C op_Addition(C, C)". Fortunately, this behavior simply // falls out of treating user-defined operators as ordinary methods; we do // not need any special handling in this method. // // However, we must have special handling for conversions because conversions // use a completely different rule for detecting collisions between two // conversions: conversion signatures consist only of the source and target // types of the conversions, and not the kind of the conversion (implicit or explicit), // the name of the method, and so on. // // Therefore we must detect the following kinds of member name conflicts: // // 1. a method, conversion or field has the same name as a (different) field (* see note below) // 2. a method has the same method signature as another method or conversion // 3. a conversion has the same conversion signature as another conversion. // // However, we must *not* detect "a conversion has the same *method* signature // as another conversion" because conversions are allowed to overload on // return type but methods are not. // // (*) NOTE: Throughout the rest of this method I will use "field" as a shorthand for // "non-method, non-conversion, non-type member", rather than spelling out // "field, property or event...") foreach (var pair in membersByName) { var name = pair.Key; Symbol? lastSym = GetTypeMembers(name).FirstOrDefault(); methodsBySignature.Clear(); // Conversion collisions do not consider the name of the conversion, // so do not clear that dictionary. foreach (var symbol in pair.Value) { if (symbol.Kind == SymbolKind.NamedType || symbol.IsAccessor() || symbol.IsIndexer()) { continue; } // We detect the first category of conflict by running down the list of members // of the same name, and producing an error when we discover any of the following // "bad transitions". // // * a method or conversion that comes after any field (not necessarily directly) // * a field directly following a field // * a field directly following a method or conversion // // Furthermore: we do not wish to detect collisions between nested types in // this code; that is tested elsewhere. However, we do wish to detect a collision // between a nested type and a field, method or conversion. Therefore we // initialize our "bad transition" detector with a type of the given name, // if there is one. That way we also detect the transitions of "method following // type", and so on. // // The "lastSym" local below is used to detect these transitions. Its value is // one of the following: // // * a nested type of the given name, or // * the first method of the given name, or // * the most recently processed field of the given name. // // If either the current symbol or the "last symbol" are not methods then // there must be a collision: // // * if the current symbol is not a method and the last symbol is, then // there is a field directly following a method of the same name // * if the current symbol is a method and the last symbol is not, then // there is a method directly or indirectly following a field of the same name, // or a method of the same name as a nested type. // * if neither are methods then either we have a field directly // following a field of the same name, or a field and a nested type of the same name. // if (lastSym is object) { if (symbol.Kind != SymbolKind.Method || lastSym.Kind != SymbolKind.Method) { if (symbol.Kind != SymbolKind.Field || !symbol.IsImplicitlyDeclared) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, symbol.Locations[0], this, symbol.Name); } } if (lastSym.Kind == SymbolKind.Method) { lastSym = symbol; } } } else { lastSym = symbol; } // That takes care of the first category of conflict; we detect the // second and third categories as follows: var conversion = symbol as SourceUserDefinedConversionSymbol; var method = symbol as SourceMemberMethodSymbol; if (!(conversion is null)) { // Does this conversion collide *as a conversion* with any previously-seen // conversion? if (!conversionsAsConversions.Add(conversion)) { // CS0557: Duplicate user-defined conversion in type 'C' diagnostics.Add(ErrorCode.ERR_DuplicateConversionInClass, conversion.Locations[0], this); } else { // The other set might already contain a conversion which would collide // *as a method* with the current conversion. if (!conversionsAsMethods.ContainsKey(conversion)) { conversionsAsMethods.Add(conversion, conversion); } } // Does this conversion collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(conversion, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, conversion, previousMethod); } // Do not add the conversion to the set of previously-seen methods; that set // is only non-conversion methods. } else if (!(method is null)) { // Does this method collide *as a method* with any previously-seen // conversion? if (conversionsAsMethods.TryGetValue(method, out var previousConversion)) { ReportMethodSignatureCollision(diagnostics, method, previousConversion); } // Do not add the method to the set of previously-seen conversions. // Does this method collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(method, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, method, previousMethod); } else { // We haven't seen this method before. Make a note of it in case // we see a colliding method later. methodsBySignature.Add(method, method); } } } } } // Report a name conflict; the error is reported on the location of method1. // UNDONE: Consider adding a secondary location pointing to the second method. private void ReportMethodSignatureCollision(BindingDiagnosticBag diagnostics, SourceMemberMethodSymbol method1, SourceMemberMethodSymbol method2) { switch (method1, method2) { case (SourceOrdinaryMethodSymbol { IsPartialDefinition: true }, SourceOrdinaryMethodSymbol { IsPartialImplementation: true }): case (SourceOrdinaryMethodSymbol { IsPartialImplementation: true }, SourceOrdinaryMethodSymbol { IsPartialDefinition: true }): // these could be 2 parts of the same partial method. // Partial methods are allowed to collide by signature. return; case (SynthesizedSimpleProgramEntryPointSymbol { }, SynthesizedSimpleProgramEntryPointSymbol { }): return; } // If method1 is a constructor only because its return type is missing, then // we've already produced a diagnostic for the missing return type and we suppress the // diagnostic about duplicate signature. if (method1.MethodKind == MethodKind.Constructor && ((ConstructorDeclarationSyntax)method1.SyntaxRef.GetSyntax()).Identifier.ValueText != this.Name) { return; } Debug.Assert(method1.ParameterCount == method2.ParameterCount); for (int i = 0; i < method1.ParameterCount; i++) { var refKind1 = method1.Parameters[i].RefKind; var refKind2 = method2.Parameters[i].RefKind; if (refKind1 != refKind2) { // '{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}' var methodKind = method1.MethodKind == MethodKind.Constructor ? MessageID.IDS_SK_CONSTRUCTOR : MessageID.IDS_SK_METHOD; diagnostics.Add(ErrorCode.ERR_OverloadRefKind, method1.Locations[0], this, methodKind.Localize(), refKind1.ToParameterDisplayString(), refKind2.ToParameterDisplayString()); return; } } // Special case: if there are two destructors, use the destructor syntax instead of "Finalize" var methodName = (method1.MethodKind == MethodKind.Destructor && method2.MethodKind == MethodKind.Destructor) ? "~" + this.Name : (method1.IsConstructor() ? this.Name : method1.Name); // Type '{1}' already defines a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, method1.Locations[0], methodName, this); } private void CheckIndexerNameConflicts(BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName) { PooledHashSet<string>? typeParameterNames = null; if (this.Arity > 0) { typeParameterNames = PooledHashSet<string>.GetInstance(); foreach (TypeParameterSymbol typeParameter in this.TypeParameters) { typeParameterNames.Add(typeParameter.Name); } } var indexersBySignature = new Dictionary<PropertySymbol, PropertySymbol>(MemberSignatureComparer.DuplicateSourceComparer); // Note: Can't assume that all indexers are called WellKnownMemberNames.Indexer because // they may be explicit interface implementations. foreach (var members in membersByName.Values) { string? lastIndexerName = null; indexersBySignature.Clear(); foreach (var symbol in members) { if (symbol.IsIndexer()) { PropertySymbol indexer = (PropertySymbol)symbol; CheckIndexerSignatureCollisions( indexer, diagnostics, membersByName, indexersBySignature, ref lastIndexerName); // Also check for collisions with type parameters, which aren't in the member map. // NOTE: Accessors have normal names and are handled in CheckTypeParameterNameConflicts. if (typeParameterNames != null) { string indexerName = indexer.MetadataName; if (typeParameterNames.Contains(indexerName)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); continue; } } } } } typeParameterNames?.Free(); } private void CheckIndexerSignatureCollisions( PropertySymbol indexer, BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<PropertySymbol, PropertySymbol> indexersBySignature, ref string? lastIndexerName) { if (!indexer.IsExplicitInterfaceImplementation) //explicit implementation names are not checked { string indexerName = indexer.MetadataName; if (lastIndexerName != null && lastIndexerName != indexerName) { // NOTE: dev10 checks indexer names by comparing each to the previous. // For example, if indexers are declared with names A, B, A, B, then there // will be three errors - one for each time the name is different from the // previous one. If, on the other hand, the names are A, A, B, B, then // there will only be one error because only one indexer has a different // name from the previous one. diagnostics.Add(ErrorCode.ERR_InconsistentIndexerNames, indexer.Locations[0]); } lastIndexerName = indexerName; if (Locations.Length == 1 || IsPartial) { if (membersByName.ContainsKey(indexerName)) { // The name of the indexer is reserved - it can only be used by other indexers. Debug.Assert(!membersByName[indexerName].Any(SymbolExtensions.IsIndexer)); diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); } } } if (indexersBySignature.TryGetValue(indexer, out var prevIndexerBySignature)) { // Type '{1}' already defines a member called '{0}' with the same parameter types // NOTE: Dev10 prints "this" as the name of the indexer. diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, indexer.Locations[0], SyntaxFacts.GetText(SyntaxKind.ThisKeyword), this); } else { indexersBySignature[indexer] = indexer; } } private void CheckSpecialMemberErrors(BindingDiagnosticBag diagnostics) { var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary); foreach (var member in this.GetMembersUnordered()) { member.AfterAddingTypeMembersChecks(conversions, diagnostics); } } private void CheckTypeParameterNameConflicts(BindingDiagnosticBag diagnostics) { if (this.TypeKind == TypeKind.Delegate) { // Delegates do not have conflicts between their type parameter // names and their methods; it is legal (though odd) to say // delegate void D<Invoke>(Invoke x); return; } if (Locations.Length == 1 || IsPartial) { foreach (var tp in TypeParameters) { foreach (var dup in GetMembers(tp.Name)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, dup.Locations[0], this, tp.Name); } } } } private void CheckAccessorNameConflicts(BindingDiagnosticBag diagnostics) { // Report errors where property and event accessors // conflict with other members of the same name. foreach (Symbol symbol in this.GetMembersUnordered()) { if (symbol.IsExplicitInterfaceImplementation()) { // If there's a name conflict it will show up as a more specific // interface implementation error. continue; } switch (symbol.Kind) { case SymbolKind.Property: { var propertySymbol = (PropertySymbol)symbol; this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: true, diagnostics: diagnostics); this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: false, diagnostics: diagnostics); break; } case SymbolKind.Event: { var eventSymbol = (EventSymbol)symbol; this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: true, diagnostics: diagnostics); this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: false, diagnostics: diagnostics); break; } } } } internal override bool KnownCircularStruct { get { if (_lazyKnownCircularStruct == (int)ThreeState.Unknown) { if (TypeKind != TypeKind.Struct) { Interlocked.CompareExchange(ref _lazyKnownCircularStruct, (int)ThreeState.False, (int)ThreeState.Unknown); } else { var diagnostics = BindingDiagnosticBag.GetInstance(); var value = (int)CheckStructCircularity(diagnostics).ToThreeState(); if (Interlocked.CompareExchange(ref _lazyKnownCircularStruct, value, (int)ThreeState.Unknown) == (int)ThreeState.Unknown) { AddDeclarationDiagnostics(diagnostics); } Debug.Assert(value == _lazyKnownCircularStruct); diagnostics.Free(); } } return _lazyKnownCircularStruct == (int)ThreeState.True; } } private bool CheckStructCircularity(BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); CheckFiniteFlatteningGraph(diagnostics); return HasStructCircularity(diagnostics); } private bool HasStructCircularity(BindingDiagnosticBag diagnostics) { foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member.Kind != SymbolKind.Field) { // NOTE: don't have to check field-like events, because they can't have struct types. continue; } var field = (FieldSymbol)member; if (field.IsStatic) { continue; } var type = field.NonPointerType(); if (((object)type != null) && (type.TypeKind == TypeKind.Struct) && BaseTypeAnalysis.StructDependsOn((NamedTypeSymbol)type, this) && !type.IsPrimitiveRecursiveStruct()) // allow System.Int32 to contain a field of its own type { // If this is a backing field, report the error on the associated property. var symbol = field.AssociatedSymbol ?? field; if (symbol.Kind == SymbolKind.Parameter) { // We should stick to members for this error. symbol = field; } // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, symbol.Locations[0], symbol, type); return true; } } } return false; } private void CheckForProtectedInStaticClass(BindingDiagnosticBag diagnostics) { if (!IsStatic) { return; } // no protected members allowed foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member is TypeSymbol) { // Duplicate Dev10's failure to diagnose this error. continue; } if (member.DeclaredAccessibility.HasProtected()) { if (member.Kind != SymbolKind.Method || ((MethodSymbol)member).MethodKind != MethodKind.Destructor) { diagnostics.Add(ErrorCode.ERR_ProtectedInStatic, member.Locations[0], member); } } } } } private void CheckForUnmatchedOperators(BindingDiagnosticBag diagnostics) { // SPEC: The true and false unary operators require pairwise declaration. // SPEC: A compile-time error occurs if a class or struct declares one // SPEC: of these operators without also declaring the other. // // SPEC DEFICIENCY: The line of the specification quoted above should say // the same thing as the lines below: that the formal parameters of the // paired true/false operators must match exactly. You can't do // op true(S) and op false(S?) for example. // SPEC: Certain binary operators require pairwise declaration. For every // SPEC: declaration of either operator of a pair, there must be a matching // SPEC: declaration of the other operator of the pair. Two operator // SPEC: declarations match when they have the same return type and the same // SPEC: type for each parameter. The following operators require pairwise // SPEC: declaration: == and !=, > and <, >= and <=. CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.TrueOperatorName, WellKnownMemberNames.FalseOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.EqualityOperatorName, WellKnownMemberNames.InequalityOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOperatorName, WellKnownMemberNames.GreaterThanOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOrEqualOperatorName, WellKnownMemberNames.GreaterThanOrEqualOperatorName); // We also produce a warning if == / != is overridden without also overriding // Equals and GetHashCode, or if Equals is overridden without GetHashCode. CheckForEqualityAndGetHashCode(diagnostics); } private void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, string operatorName1, string operatorName2) { var ops1 = this.GetOperators(operatorName1); var ops2 = this.GetOperators(operatorName2); CheckForUnmatchedOperator(diagnostics, ops1, ops2, operatorName2); CheckForUnmatchedOperator(diagnostics, ops2, ops1, operatorName1); } private static void CheckForUnmatchedOperator( BindingDiagnosticBag diagnostics, ImmutableArray<MethodSymbol> ops1, ImmutableArray<MethodSymbol> ops2, string operatorName2) { foreach (var op1 in ops1) { bool foundMatch = false; foreach (var op2 in ops2) { foundMatch = DoOperatorsPair(op1, op2); if (foundMatch) { break; } } if (!foundMatch) { // CS0216: The operator 'C.operator true(C)' requires a matching operator 'false' to also be defined diagnostics.Add(ErrorCode.ERR_OperatorNeedsMatch, op1.Locations[0], op1, SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName2))); } } } private static bool DoOperatorsPair(MethodSymbol op1, MethodSymbol op2) { if (op1.ParameterCount != op2.ParameterCount) { return false; } for (int p = 0; p < op1.ParameterCount; ++p) { if (!op1.ParameterTypesWithAnnotations[p].Equals(op2.ParameterTypesWithAnnotations[p], TypeCompareKind.AllIgnoreOptions)) { return false; } } if (!op1.ReturnType.Equals(op2.ReturnType, TypeCompareKind.AllIgnoreOptions)) { return false; } return true; } private void CheckForEqualityAndGetHashCode(BindingDiagnosticBag diagnostics) { if (this.IsInterfaceType()) { // Interfaces are allowed to define Equals without GetHashCode if they want. return; } if (IsRecord || IsRecordStruct) { // For records the warnings reported below are simply going to echo record specific errors, // producing more noise. return; } bool hasOp = this.GetOperators(WellKnownMemberNames.EqualityOperatorName).Any() || this.GetOperators(WellKnownMemberNames.InequalityOperatorName).Any(); bool overridesEquals = this.TypeOverridesObjectMethod("Equals"); if (hasOp || overridesEquals) { bool overridesGHC = this.TypeOverridesObjectMethod("GetHashCode"); if (overridesEquals && !overridesGHC) { // CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualsWithoutGetHashCode, this.Locations[0], this); } if (hasOp && !overridesEquals) { // CS0660: 'C' defines operator == or operator != but does not override Object.Equals(object o) diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutEquals, this.Locations[0], this); } if (hasOp && !overridesGHC) { // CS0661: 'C' defines operator == or operator != but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutGetHashCode, this.Locations[0], this); } } } private bool TypeOverridesObjectMethod(string name) { foreach (var method in this.GetMembers(name).OfType<MethodSymbol>()) { if (method.IsOverride && method.GetConstructedLeastOverriddenMethod(this, requireSameReturnType: false).ContainingType.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object) { return true; } } return false; } private void CheckFiniteFlatteningGraph(BindingDiagnosticBag diagnostics) { Debug.Assert(ReferenceEquals(this, this.OriginalDefinition)); if (AllTypeArgumentCount() == 0) return; var instanceMap = new Dictionary<NamedTypeSymbol, NamedTypeSymbol>(ReferenceEqualityComparer.Instance); instanceMap.Add(this, this); foreach (var m in this.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(this, type, instanceMap)) { // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, f.Locations[0], f, type); //this.KnownCircularStruct = true; return; } } } private static bool InfiniteFlatteningGraph(SourceMemberContainerTypeSymbol top, NamedTypeSymbol t, Dictionary<NamedTypeSymbol, NamedTypeSymbol> instanceMap) { if (!t.ContainsTypeParameter()) return false; var tOriginal = t.OriginalDefinition; if (instanceMap.TryGetValue(tOriginal, out var oldInstance)) { // short circuit when we find a cycle, but only return true when the cycle contains the top struct return (!TypeSymbol.Equals(oldInstance, t, TypeCompareKind.AllNullableIgnoreOptions)) && ReferenceEquals(tOriginal, top); } else { instanceMap.Add(tOriginal, t); try { foreach (var m in t.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(top, type, instanceMap)) return true; } return false; } finally { instanceMap.Remove(tOriginal); } } } private void CheckSequentialOnPartialType(BindingDiagnosticBag diagnostics) { if (!IsPartial || this.Layout.Kind != LayoutKind.Sequential) { return; } SyntaxReference? whereFoundField = null; if (this.SyntaxReferences.Length <= 1) { return; } foreach (var syntaxRef in this.SyntaxReferences) { var syntax = syntaxRef.GetSyntax() as TypeDeclarationSyntax; if (syntax == null) { continue; } foreach (var m in syntax.Members) { if (HasInstanceData(m)) { if (whereFoundField != null && whereFoundField != syntaxRef) { diagnostics.Add(ErrorCode.WRN_SequentialOnPartialClass, Locations[0], this); return; } whereFoundField = syntaxRef; } } } } private static bool HasInstanceData(MemberDeclarationSyntax m) { switch (m.Kind()) { case SyntaxKind.FieldDeclaration: var fieldDecl = (FieldDeclarationSyntax)m; return !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.ConstKeyword); case SyntaxKind.PropertyDeclaration: // auto-property var propertyDecl = (PropertyDeclarationSyntax)m; return !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.ExternKeyword) && propertyDecl.AccessorList != null && All(propertyDecl.AccessorList.Accessors, a => a.Body == null && a.ExpressionBody == null); case SyntaxKind.EventFieldDeclaration: // field-like event declaration var eventFieldDecl = (EventFieldDeclarationSyntax)m; return !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.ExternKeyword); default: return false; } } private static bool All<T>(SyntaxList<T> list, Func<T, bool> predicate) where T : CSharpSyntaxNode { foreach (var t in list) { if (predicate(t)) return true; }; return false; } private static bool ContainsModifier(SyntaxTokenList modifiers, SyntaxKind modifier) { foreach (var m in modifiers) { if (m.IsKind(modifier)) return true; }; return false; } private Dictionary<string, ImmutableArray<Symbol>> MakeAllMembers(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName; var membersAndInitializers = GetMembersAndInitializers(); // Most types don't have indexers. If this is one of those types, // just reuse the dictionary we build for early attribute decoding. // For tuples, we also need to take the slow path. if (!membersAndInitializers.HaveIndexers && !this.IsTupleType && _lazyEarlyAttributeDecodingMembersDictionary is object) { membersByName = _lazyEarlyAttributeDecodingMembersDictionary; } else { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name, StringOrdinalComparer.Instance); // Merge types into the member dictionary AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); } MergePartialMembers(ref membersByName, diagnostics); return membersByName; } private static void AddNestedTypesToDictionary(Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<string, ImmutableArray<NamedTypeSymbol>> typesByName) { foreach (var pair in typesByName) { string name = pair.Key; ImmutableArray<NamedTypeSymbol> types = pair.Value; ImmutableArray<Symbol> typesAsSymbols = StaticCast<Symbol>.From(types); ImmutableArray<Symbol> membersForName; if (membersByName.TryGetValue(name, out membersForName)) { membersByName[name] = membersForName.Concat(typesAsSymbols); } else { membersByName.Add(name, typesAsSymbols); } } } private sealed class DeclaredMembersAndInitializersBuilder { public ArrayBuilder<Symbol> NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> StaticInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> InstanceInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public bool HaveIndexers; public RecordDeclarationSyntax? RecordDeclarationWithParameters; public SynthesizedRecordConstructor? RecordPrimaryConstructor; public bool IsNullableEnabledForInstanceConstructorsAndFields; public bool IsNullableEnabledForStaticConstructorsAndFields; public DeclaredMembersAndInitializers ToReadOnlyAndFree(CSharpCompilation compilation) { return new DeclaredMembersAndInitializers( NonTypeMembers.ToImmutableAndFree(), MembersAndInitializersBuilder.ToReadOnlyAndFree(StaticInitializers), MembersAndInitializersBuilder.ToReadOnlyAndFree(InstanceInitializers), HaveIndexers, RecordDeclarationWithParameters, RecordPrimaryConstructor, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields, compilation); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, bool value) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || value; } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } public void Free() { NonTypeMembers.Free(); foreach (var group in StaticInitializers) { group.Free(); } StaticInitializers.Free(); foreach (var group in InstanceInitializers) { group.Free(); } InstanceInitializers.Free(); } internal void AddOrWrapTupleMembers(SourceMemberContainerTypeSymbol type) { this.NonTypeMembers = type.AddOrWrapTupleMembers(this.NonTypeMembers.ToImmutableAndFree()); } } private sealed class SimpleProgramEntryPointInfo { public readonly ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> SimpleProgramEntryPoints; public static readonly SimpleProgramEntryPointInfo UninitializedSentinel = new SimpleProgramEntryPointInfo(); private SimpleProgramEntryPointInfo() { } public SimpleProgramEntryPointInfo(ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> simpleProgramEntryPoints) { Debug.Assert(simpleProgramEntryPoints.All(ep => ep is not null)); this.SimpleProgramEntryPoints = simpleProgramEntryPoints; } } protected sealed class DeclaredMembersAndInitializers { public readonly ImmutableArray<Symbol> NonTypeMembers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; public readonly bool HaveIndexers; public readonly RecordDeclarationSyntax? RecordDeclarationWithParameters; public readonly SynthesizedRecordConstructor? RecordPrimaryConstructor; public readonly bool IsNullableEnabledForInstanceConstructorsAndFields; public readonly bool IsNullableEnabledForStaticConstructorsAndFields; public static readonly DeclaredMembersAndInitializers UninitializedSentinel = new DeclaredMembersAndInitializers(); private DeclaredMembersAndInitializers() { } public DeclaredMembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, RecordDeclarationSyntax? recordDeclarationWithParameters, SynthesizedRecordConstructor? recordPrimaryConstructor, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields, CSharpCompilation compilation) { Debug.Assert(!nonTypeMembers.IsDefault); AssertInitializers(staticInitializers, compilation); AssertInitializers(instanceInitializers, compilation); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(recordDeclarationWithParameters is object == recordPrimaryConstructor is object); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.RecordDeclarationWithParameters = recordDeclarationWithParameters; this.RecordPrimaryConstructor = recordPrimaryConstructor; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } [Conditional("DEBUG")] public static void AssertInitializers(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, CSharpCompilation compilation) { Debug.Assert(!initializers.IsDefault); if (initializers.IsEmpty) { return; } foreach (ImmutableArray<FieldOrPropertyInitializer> group in initializers) { Debug.Assert(!group.IsDefaultOrEmpty); } for (int i = 0; i < initializers.Length; i++) { if (i > 0) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i - 1].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } if (i + 1 < initializers.Length) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i + 1].Last().Syntax, compilation)) < 0); } if (initializers[i].Length != 1) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } } } } private sealed class MembersAndInitializersBuilder { public ArrayBuilder<Symbol>? NonTypeMembers; private ArrayBuilder<FieldOrPropertyInitializer>? InstanceInitializersForPositionalMembers; private bool IsNullableEnabledForInstanceConstructorsAndFields; private bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializersBuilder(DeclaredMembersAndInitializers declaredMembersAndInitializers) { Debug.Assert(declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel); this.IsNullableEnabledForInstanceConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields; } public MembersAndInitializers ToReadOnlyAndFree(DeclaredMembersAndInitializers declaredMembers) { var nonTypeMembers = NonTypeMembers?.ToImmutableAndFree() ?? declaredMembers.NonTypeMembers; var instanceInitializers = InstanceInitializersForPositionalMembers is null ? declaredMembers.InstanceInitializers : mergeInitializers(); return new MembersAndInitializers( nonTypeMembers, declaredMembers.StaticInitializers, instanceInitializers, declaredMembers.HaveIndexers, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields); ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> mergeInitializers() { Debug.Assert(InstanceInitializersForPositionalMembers.Count != 0); Debug.Assert(declaredMembers.RecordPrimaryConstructor is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.SyntaxTree == InstanceInitializersForPositionalMembers[0].Syntax.SyntaxTree); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.Span.Contains(InstanceInitializersForPositionalMembers[0].Syntax.Span.Start)); var groupCount = declaredMembers.InstanceInitializers.Length; if (groupCount == 0) { return ImmutableArray.Create(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); } var compilation = declaredMembers.RecordPrimaryConstructor.DeclaringCompilation; var sortKey = new LexicalSortKey(InstanceInitializersForPositionalMembers.First().Syntax, compilation); int insertAt; for (insertAt = 0; insertAt < groupCount; insertAt++) { if (LexicalSortKey.Compare(sortKey, new LexicalSortKey(declaredMembers.InstanceInitializers[insertAt][0].Syntax, compilation)) < 0) { break; } } ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> groupsBuilder; if (insertAt != groupCount && declaredMembers.RecordDeclarationWithParameters.SyntaxTree == declaredMembers.InstanceInitializers[insertAt][0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(declaredMembers.InstanceInitializers[insertAt][0].Syntax.Span.Start)) { // Need to merge into the previous group var declaredInitializers = declaredMembers.InstanceInitializers[insertAt]; var insertedInitializers = InstanceInitializersForPositionalMembers; #if DEBUG // initializers should be added in syntax order: Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.SyntaxTree == declaredInitializers[0].Syntax.SyntaxTree); Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.Span.Start < declaredInitializers[0].Syntax.Span.Start); #endif insertedInitializers.AddRange(declaredInitializers); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(insertedInitializers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt + 1, groupCount - (insertAt + 1)); Debug.Assert(groupsBuilder.Count == groupCount); } else { Debug.Assert(!declaredMembers.InstanceInitializers.Any(g => declaredMembers.RecordDeclarationWithParameters.SyntaxTree == g[0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(g[0].Syntax.Span.Start))); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount + 1); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt, groupCount - insertAt); Debug.Assert(groupsBuilder.Count == groupCount + 1); } var result = groupsBuilder.ToImmutableAndFree(); DeclaredMembersAndInitializers.AssertInitializers(result, compilation); return result; } } public void AddInstanceInitializerForPositionalMembers(FieldOrPropertyInitializer initializer) { if (InstanceInitializersForPositionalMembers is null) { InstanceInitializersForPositionalMembers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } InstanceInitializersForPositionalMembers.Add(initializer); } public IReadOnlyCollection<Symbol> GetNonTypeMembers(DeclaredMembersAndInitializers declaredMembers) { return NonTypeMembers ?? (IReadOnlyCollection<Symbol>)declaredMembers.NonTypeMembers; } public void AddNonTypeMember(Symbol member, DeclaredMembersAndInitializers declaredMembers) { if (NonTypeMembers is null) { NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(declaredMembers.NonTypeMembers.Length + 1); NonTypeMembers.AddRange(declaredMembers.NonTypeMembers); } NonTypeMembers.Add(member); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } internal static ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> ToReadOnlyAndFree(ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> initializers) { if (initializers.Count == 0) { initializers.Free(); return ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>>.Empty; } var builder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(initializers.Count); foreach (ArrayBuilder<FieldOrPropertyInitializer> group in initializers) { builder.Add(group.ToImmutableAndFree()); } initializers.Free(); return builder.ToImmutableAndFree(); } public void Free() { NonTypeMembers?.Free(); InstanceInitializersForPositionalMembers?.Free(); } } protected MembersAndInitializers? BuildMembersAndInitializers(BindingDiagnosticBag diagnostics) { var declaredMembersAndInitializers = getDeclaredMembersAndInitializers(); if (declaredMembersAndInitializers is null) { // Another thread completed the work before this one return null; } var membersAndInitializersBuilder = new MembersAndInitializersBuilder(declaredMembersAndInitializers); AddSynthesizedMembers(membersAndInitializersBuilder, declaredMembersAndInitializers, diagnostics); if (Volatile.Read(ref _lazyMembersAndInitializers) != null) { // Another thread completed the work before this one membersAndInitializersBuilder.Free(); return null; } return membersAndInitializersBuilder.ToReadOnlyAndFree(declaredMembersAndInitializers); DeclaredMembersAndInitializers? getDeclaredMembersAndInitializers() { var declaredMembersAndInitializers = _lazyDeclaredMembersAndInitializers; if (declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel) { return declaredMembersAndInitializers; } if (Volatile.Read(ref _lazyMembersAndInitializers) is not null) { // We're previously computed declared members and already cleared them out // No need to compute them again return null; } var diagnostics = BindingDiagnosticBag.GetInstance(); declaredMembersAndInitializers = buildDeclaredMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyDeclaredMembersAndInitializers, declaredMembersAndInitializers, DeclaredMembersAndInitializers.UninitializedSentinel); if (alreadyKnown != DeclaredMembersAndInitializers.UninitializedSentinel) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); return declaredMembersAndInitializers!; } // Builds explicitly declared members (as opposed to synthesized members). // This should not attempt to bind any method parameters as that would cause // the members being built to be captured in the binder cache before the final // list of members is determined. DeclaredMembersAndInitializers? buildDeclaredMembersAndInitializers(BindingDiagnosticBag diagnostics) { var builder = new DeclaredMembersAndInitializersBuilder(); AddDeclaredNontypeMembers(builder, diagnostics); switch (TypeKind) { case TypeKind.Struct: CheckForStructBadInitializers(builder, diagnostics); CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: false, diagnostics: diagnostics); break; case TypeKind.Enum: CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: true, diagnostics: diagnostics); break; case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: // No additional checking required. break; default: break; } if (IsTupleType) { builder.AddOrWrapTupleMembers(this); } if (Volatile.Read(ref _lazyDeclaredMembersAndInitializers) != DeclaredMembersAndInitializers.UninitializedSentinel) { // _lazyDeclaredMembersAndInitializers is already computed. no point to continue. builder.Free(); return null; } return builder.ToReadOnlyAndFree(DeclaringCompilation); } } internal ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> GetSimpleProgramEntryPoints() { if (this.ContainingSymbol is not NamespaceSymbol { IsGlobalNamespace: true } || this.Name != WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) { return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; } SimpleProgramEntryPointInfo? simpleProgramEntryPointInfo = _lazySimpleProgramEntryPoint; if (simpleProgramEntryPointInfo == SimpleProgramEntryPointInfo.UninitializedSentinel) { var diagnostics = BindingDiagnosticBag.GetInstance(); simpleProgramEntryPointInfo = buildSimpleProgramEntryPoint(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazySimpleProgramEntryPoint, simpleProgramEntryPointInfo, SimpleProgramEntryPointInfo.UninitializedSentinel); if (alreadyKnown == SimpleProgramEntryPointInfo.UninitializedSentinel) { AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _lazySimpleProgramEntryPoint?.SimpleProgramEntryPoints ?? ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; SimpleProgramEntryPointInfo? buildSimpleProgramEntryPoint(BindingDiagnosticBag diagnostics) { ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>? builder = null; foreach (var singleDecl in declaration.Declarations) { if (singleDecl.IsSimpleProgram) { if (builder is null) { builder = ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>.GetInstance(); } else { Binder.Error(diagnostics, ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, singleDecl.NameLocation); } builder.Add(new SynthesizedSimpleProgramEntryPointSymbol(this, singleDecl, diagnostics)); } } if (builder is null) { return null; } return new SimpleProgramEntryPointInfo(builder.ToImmutableAndFree()); } } private void AddSynthesizedMembers(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (TypeKind is TypeKind.Class) { AddSynthesizedSimpleProgramEntryPointIfNecessary(builder, declaredMembersAndInitializers, diagnostics); } switch (TypeKind) { case TypeKind.Struct: case TypeKind.Enum: case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: AddSynthesizedRecordMembersIfNecessary(builder, declaredMembersAndInitializers, diagnostics); AddSynthesizedConstructorsIfNecessary(builder, declaredMembersAndInitializers, diagnostics); break; default: break; } } private void AddDeclaredNontypeMembers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { foreach (var decl in this.declaration.Declarations) { if (!decl.HasAnyNontypeMembers) { continue; } if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } var syntax = decl.SyntaxReference.GetSyntax(); switch (syntax.Kind()) { case SyntaxKind.EnumDeclaration: AddEnumMembers(builder, (EnumDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.DelegateDeclaration: SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeMembers, (DelegateDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // The members of a global anonymous type is in a syntax tree of a namespace declaration or a compilation unit. AddNonTypeMembers(builder, ((BaseNamespaceDeclarationSyntax)syntax).Members, diagnostics); break; case SyntaxKind.CompilationUnit: AddNonTypeMembers(builder, ((CompilationUnitSyntax)syntax).Members, diagnostics); break; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)syntax; AddNonTypeMembers(builder, typeDecl.Members, diagnostics); break; case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var recordDecl = (RecordDeclarationSyntax)syntax; var parameterList = recordDecl.ParameterList; noteRecordParameters(recordDecl, parameterList, builder, diagnostics); AddNonTypeMembers(builder, recordDecl.Members, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } void noteRecordParameters(RecordDeclarationSyntax syntax, ParameterListSyntax? parameterList, DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { if (parameterList is null) { return; } if (builder.RecordDeclarationWithParameters is null) { builder.RecordDeclarationWithParameters = syntax; var ctor = new SynthesizedRecordConstructor(this, syntax); builder.RecordPrimaryConstructor = ctor; var compilation = DeclaringCompilation; builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, parameterList); if (syntax is { PrimaryConstructorBaseTypeIfClass: { ArgumentList: { } baseParamList } }) { builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, baseParamList); } } else { diagnostics.Add(ErrorCode.ERR_MultipleRecordParameterLists, parameterList.Location); } } } internal Binder GetBinder(CSharpSyntaxNode syntaxNode) { return this.DeclaringCompilation.GetBinder(syntaxNode); } private void MergePartialMembers( ref Dictionary<string, ImmutableArray<Symbol>> membersByName, BindingDiagnosticBag diagnostics) { var memberNames = ArrayBuilder<string>.GetInstance(membersByName.Count); memberNames.AddRange(membersByName.Keys); //key and value will be the same object var methodsBySignature = new Dictionary<MethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.PartialMethodsComparer); foreach (var name in memberNames) { methodsBySignature.Clear(); foreach (var symbol in membersByName[name]) { var method = symbol as SourceMemberMethodSymbol; if (method is null || !method.IsPartial) { continue; // only partial methods need to be merged } if (methodsBySignature.TryGetValue(method, out var prev)) { var prevPart = (SourceOrdinaryMethodSymbol)prev; var methodPart = (SourceOrdinaryMethodSymbol)method; if (methodPart.IsPartialImplementation && (prevPart.IsPartialImplementation || (prevPart.OtherPartOfPartial is MethodSymbol otherImplementation && (object)otherImplementation != methodPart))) { // A partial method may not have multiple implementing declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneActual, methodPart.Locations[0]); } else if (methodPart.IsPartialDefinition && (prevPart.IsPartialDefinition || (prevPart.OtherPartOfPartial is MethodSymbol otherDefinition && (object)otherDefinition != methodPart))) { // A partial method may not have multiple defining declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneLatent, methodPart.Locations[0]); } else { if ((object)membersByName == _lazyEarlyAttributeDecodingMembersDictionary) { // Avoid mutating the cached dictionary and especially avoid doing this possibly on multiple threads in parallel. membersByName = new Dictionary<string, ImmutableArray<Symbol>>(membersByName); } membersByName[name] = FixPartialMember(membersByName[name], prevPart, methodPart); } } else { methodsBySignature.Add(method, method); } } foreach (SourceOrdinaryMethodSymbol method in methodsBySignature.Values) { // partial implementations not paired with a definition if (method.IsPartialImplementation && method.OtherPartOfPartial is null) { diagnostics.Add(ErrorCode.ERR_PartialMethodMustHaveLatent, method.Locations[0], method); } else if (method is { IsPartialDefinition: true, OtherPartOfPartial: null, HasExplicitAccessModifier: true }) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, method.Locations[0], method); } } } memberNames.Free(); } /// <summary> /// Fix up a partial method by combining its defining and implementing declarations, updating the array of symbols (by name), /// and returning the combined symbol. /// </summary> /// <param name="symbols">The symbols array containing both the latent and implementing declaration</param> /// <param name="part1">One of the two declarations</param> /// <param name="part2">The other declaration</param> /// <returns>An updated symbols array containing only one method symbol representing the two parts</returns> private static ImmutableArray<Symbol> FixPartialMember(ImmutableArray<Symbol> symbols, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2) { SourceOrdinaryMethodSymbol definition; SourceOrdinaryMethodSymbol implementation; if (part1.IsPartialDefinition) { definition = part1; implementation = part2; } else { definition = part2; implementation = part1; } SourceOrdinaryMethodSymbol.InitializePartialMethodParts(definition, implementation); // a partial method is represented in the member list by its definition part: return Remove(symbols, implementation); } private static ImmutableArray<Symbol> Remove(ImmutableArray<Symbol> symbols, Symbol symbol) { var builder = ArrayBuilder<Symbol>.GetInstance(); foreach (var s in symbols) { if (!ReferenceEquals(s, symbol)) { builder.Add(s); } } return builder.ToImmutableAndFree(); } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the property accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithPropertyAccessor( PropertySymbol propertySymbol, bool getNotSet, BindingDiagnosticBag diagnostics) { Debug.Assert(!propertySymbol.IsExplicitInterfaceImplementation); // checked by caller MethodSymbol accessor = getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod; string accessorName; if ((object)accessor != null) { accessorName = accessor.Name; } else { string propertyName = propertySymbol.IsIndexer ? propertySymbol.MetadataName : propertySymbol.Name; accessorName = SourcePropertyAccessorSymbol.GetAccessorName(propertyName, getNotSet, propertySymbol.IsCompilationOutputWinMdObj()); } foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchPropertyAccessor(propertySymbol, getNotSet, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), accessorName, this); return; } } } } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the event accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithEventAccessor( EventSymbol eventSymbol, bool isAdder, BindingDiagnosticBag diagnostics) { Debug.Assert(!eventSymbol.IsExplicitInterfaceImplementation); // checked by caller string accessorName = SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAdder); foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrEventLocation(eventSymbol, isAdder), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchEventAccessor(eventSymbol, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrEventLocation(eventSymbol, isAdder), accessorName, this); return; } } } } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the property. /// </summary> private static Location GetAccessorOrPropertyLocation(PropertySymbol propertySymbol, bool getNotSet) { var locationFrom = (Symbol)(getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the event. /// </summary> private static Location GetAccessorOrEventLocation(EventSymbol propertySymbol, bool isAdder) { var locationFrom = (Symbol?)(isAdder ? propertySymbol.AddMethod : propertySymbol.RemoveMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return true if the method parameters match the parameters of the /// property accessor, including the value parameter for the setter. /// </summary> private static bool ParametersMatchPropertyAccessor(PropertySymbol propertySymbol, bool getNotSet, ImmutableArray<ParameterSymbol> methodParams) { var propertyParams = propertySymbol.Parameters; var numParams = propertyParams.Length + (getNotSet ? 0 : 1); if (numParams != methodParams.Length) { return false; } for (int i = 0; i < numParams; i++) { var methodParam = methodParams[i]; if (methodParam.RefKind != RefKind.None) { return false; } var propertyParamType = (((i == numParams - 1) && !getNotSet) ? propertySymbol.TypeWithAnnotations : propertyParams[i].TypeWithAnnotations).Type; if (!propertyParamType.Equals(methodParam.Type, TypeCompareKind.AllIgnoreOptions)) { return false; } } return true; } /// <summary> /// Return true if the method parameters match the parameters of the /// event accessor, including the value parameter. /// </summary> private static bool ParametersMatchEventAccessor(EventSymbol eventSymbol, ImmutableArray<ParameterSymbol> methodParams) { return methodParams.Length == 1 && methodParams[0].RefKind == RefKind.None && eventSymbol.Type.Equals(methodParams[0].Type, TypeCompareKind.AllIgnoreOptions); } private void AddEnumMembers(DeclaredMembersAndInitializersBuilder result, EnumDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { // The previous enum constant used to calculate subsequent // implicit enum constants. (This is the most recent explicit // enum constant or the first implicit constant if no explicit values.) SourceEnumConstantSymbol? otherSymbol = null; // Offset from "otherSymbol". int otherSymbolOffset = 0; foreach (var member in syntax.Members) { SourceEnumConstantSymbol symbol; var valueOpt = member.EqualsValue; if (valueOpt != null) { symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(this, member, diagnostics); } else { symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(this, member, otherSymbol, otherSymbolOffset, diagnostics); } result.NonTypeMembers.Add(symbol); if (valueOpt != null || otherSymbol is null) { otherSymbol = symbol; otherSymbolOffset = 1; } else { otherSymbolOffset++; } } } private static void AddInitializer(ref ArrayBuilder<FieldOrPropertyInitializer>? initializers, FieldSymbol? fieldOpt, CSharpSyntaxNode node) { if (initializers == null) { initializers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } else if (initializers.Count != 0) { // initializers should be added in syntax order: Debug.Assert(node.SyntaxTree == initializers.Last().Syntax.SyntaxTree); Debug.Assert(node.SpanStart > initializers.Last().Syntax.Span.Start); } initializers.Add(new FieldOrPropertyInitializer(fieldOpt, node)); } private static void AddInitializers( ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> allInitializers, ArrayBuilder<FieldOrPropertyInitializer>? siblingsOpt) { if (siblingsOpt != null) { allInitializers.Add(siblingsOpt); } } private static void CheckInterfaceMembers(ImmutableArray<Symbol> nonTypeMembers, BindingDiagnosticBag diagnostics) { foreach (var member in nonTypeMembers) { CheckInterfaceMember(member, diagnostics); } } private static void CheckInterfaceMember(Symbol member, BindingDiagnosticBag diagnostics) { switch (member.Kind) { case SymbolKind.Field: break; case SymbolKind.Method: var meth = (MethodSymbol)member; switch (meth.MethodKind) { case MethodKind.Constructor: diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConstructors, member.Locations[0]); break; case MethodKind.Conversion: if (!meth.IsAbstract) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.UserDefinedOperator: if (!meth.IsAbstract && (meth.Name == WellKnownMemberNames.EqualityOperatorName || meth.Name == WellKnownMemberNames.InequalityOperatorName)) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.Destructor: diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, member.Locations[0]); break; case MethodKind.ExplicitInterfaceImplementation: //CS0541 is handled in SourcePropertySymbol case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRemove: case MethodKind.StaticConstructor: break; default: throw ExceptionUtilities.UnexpectedValue(meth.MethodKind); } break; case SymbolKind.Property: break; case SymbolKind.Event: break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private static void CheckForStructDefaultConstructors( ArrayBuilder<Symbol> members, bool isEnum, BindingDiagnosticBag diagnostics) { foreach (var s in members) { var m = s as MethodSymbol; if (!(m is null)) { if (m.MethodKind == MethodKind.Constructor && m.ParameterCount == 0) { var location = m.Locations[0]; if (isEnum) { diagnostics.Add(ErrorCode.ERR_EnumsCantContainDefaultConstructor, location); } else { MessageID.IDS_FeatureParameterlessStructConstructors.CheckFeatureAvailability(diagnostics, m.DeclaringCompilation, location); if (m.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicParameterlessStructConstructor, location); } } } } } } private void CheckForStructBadInitializers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); if (builder.RecordDeclarationWithParameters is not null) { Debug.Assert(builder.RecordDeclarationWithParameters is RecordDeclarationSyntax { ParameterList: not null } record && record.Kind() == SyntaxKind.RecordStructDeclaration); return; } foreach (var initializers in builder.InstanceInitializers) { foreach (FieldOrPropertyInitializer initializer in initializers) { var symbol = initializer.FieldOpt.AssociatedSymbol ?? initializer.FieldOpt; MessageID.IDS_FeatureStructFieldInitializers.CheckFeatureAvailability(diagnostics, symbol.DeclaringCompilation, symbol.Locations[0]); } } } private void AddSynthesizedSimpleProgramEntryPointIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { var simpleProgramEntryPoints = GetSimpleProgramEntryPoints(); foreach (var member in simpleProgramEntryPoints) { builder.AddNonTypeMember(member, declaredMembersAndInitializers); } } private void AddSynthesizedRecordMembersIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (declaration.Kind is not (DeclarationKind.Record or DeclarationKind.RecordStruct)) { return; } ParameterListSyntax? paramList = declaredMembersAndInitializers.RecordDeclarationWithParameters?.ParameterList; var memberSignatures = s_duplicateRecordMemberSignatureDictionary.Allocate(); var fieldsByName = PooledDictionary<string, Symbol>.GetInstance(); var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); var members = ArrayBuilder<Symbol>.GetInstance(membersSoFar.Count + 1); var memberNames = PooledHashSet<string>.GetInstance(); foreach (var member in membersSoFar) { memberNames.Add(member.Name); switch (member) { case EventSymbol: case MethodSymbol { MethodKind: not (MethodKind.Ordinary or MethodKind.Constructor) }: continue; case FieldSymbol { Name: var fieldName }: if (!fieldsByName.ContainsKey(fieldName)) { fieldsByName.Add(fieldName, member); } continue; } if (!memberSignatures.ContainsKey(member)) { memberSignatures.Add(member, member); } } CSharpCompilation compilation = this.DeclaringCompilation; bool isRecordClass = declaration.Kind == DeclarationKind.Record; // Positional record bool primaryAndCopyCtorAmbiguity = false; if (!(paramList is null)) { Debug.Assert(declaredMembersAndInitializers.RecordDeclarationWithParameters is object); // primary ctor var ctor = declaredMembersAndInitializers.RecordPrimaryConstructor; Debug.Assert(ctor is object); members.Add(ctor); if (ctor.ParameterCount != 0) { // properties and Deconstruct var existingOrAddedMembers = addProperties(ctor.Parameters); addDeconstruct(ctor, existingOrAddedMembers); } if (isRecordClass) { primaryAndCopyCtorAmbiguity = ctor.ParameterCount == 1 && ctor.Parameters[0].Type.Equals(this, TypeCompareKind.AllIgnoreOptions); } } if (isRecordClass) { addCopyCtor(primaryAndCopyCtorAmbiguity); addCloneMethod(); } PropertySymbol? equalityContract = isRecordClass ? addEqualityContract() : null; var thisEquals = addThisEquals(equalityContract); if (isRecordClass) { addBaseEquals(); } addObjectEquals(thisEquals); var getHashCode = addGetHashCode(equalityContract); addEqualityOperators(); if (thisEquals is not SynthesizedRecordEquals && getHashCode is SynthesizedRecordGetHashCode) { diagnostics.Add(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, thisEquals.Locations[0], declaration.Name); } var printMembers = addPrintMembersMethod(membersSoFar); addToStringMethod(printMembers); memberSignatures.Free(); fieldsByName.Free(); memberNames.Free(); // Synthesizing non-readonly properties in struct would require changing readonly logic for PrintMembers method synthesis Debug.Assert(isRecordClass || !members.Any(m => m is PropertySymbol { GetMethod.IsEffectivelyReadOnly : false })); // We put synthesized record members first so that errors about conflicts show up on user-defined members rather than all // going to the record declaration members.AddRange(membersSoFar); builder.NonTypeMembers?.Free(); builder.NonTypeMembers = members; return; void addDeconstruct(SynthesizedRecordConstructor ctor, ImmutableArray<Symbol> positionalMembers) { Debug.Assert(positionalMembers.All(p => p is PropertySymbol or FieldSymbol)); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.DeconstructMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ctor.Parameters.SelectAsArray<ParameterSymbol, ParameterSymbol>(param => new SignatureOnlyParameterSymbol(param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.Out )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingDeconstructMethod)) { members.Add(new SynthesizedRecordDeconstruct(this, ctor, positionalMembers, memberOffset: members.Count, diagnostics)); } else { var deconstruct = (MethodSymbol)existingDeconstructMethod; if (deconstruct.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, deconstruct.Locations[0], deconstruct); } if (deconstruct.ReturnType.SpecialType != SpecialType.System_Void && !deconstruct.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, deconstruct.Locations[0], deconstruct, targetMethod.ReturnType); } if (deconstruct.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, deconstruct.Locations[0], deconstruct); } } } void addCopyCtor(bool primaryAndCopyCtorAmbiguity) { Debug.Assert(isRecordClass); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.InstanceConstructorName, this, MethodKind.Constructor, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingConstructor)) { var copyCtor = new SynthesizedRecordCopyCtor(this, memberOffset: members.Count); members.Add(copyCtor); if (primaryAndCopyCtorAmbiguity) { diagnostics.Add(ErrorCode.ERR_RecordAmbigCtor, copyCtor.Locations[0]); } } else { var constructor = (MethodSymbol)existingConstructor; if (!this.IsSealed && (constructor.DeclaredAccessibility != Accessibility.Public && constructor.DeclaredAccessibility != Accessibility.Protected)) { diagnostics.Add(ErrorCode.ERR_CopyConstructorWrongAccessibility, constructor.Locations[0], constructor); } } } void addCloneMethod() { Debug.Assert(isRecordClass); members.Add(new SynthesizedRecordClone(this, memberOffset: members.Count, diagnostics)); } MethodSymbol addPrintMembersMethod(IEnumerable<Symbol> userDefinedMembers) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.PrintMembersMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Text_StringBuilder)), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None)), RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); MethodSymbol printMembersMethod; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingPrintMembersMethod)) { printMembersMethod = new SynthesizedRecordPrintMembers(this, userDefinedMembers, memberOffset: members.Count, diagnostics); members.Add(printMembersMethod); } else { printMembersMethod = (MethodSymbol)existingPrintMembersMethod; if (!isRecordClass || (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType())) { if (printMembersMethod.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } } else if (printMembersMethod.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } if (!printMembersMethod.ReturnType.Equals(targetMethod.ReturnType, TypeCompareKind.AllIgnoreOptions)) { if (!printMembersMethod.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, printMembersMethod.Locations[0], printMembersMethod, targetMethod.ReturnType); } } else if (isRecordClass) { SynthesizedRecordPrintMembers.VerifyOverridesPrintMembersFromBase(printMembersMethod, diagnostics); } reportStaticOrNotOverridableAPIInRecord(printMembersMethod, diagnostics); } return printMembersMethod; } void addToStringMethod(MethodSymbol printMethod) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectToString, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_String)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); var baseToStringMethod = getBaseToStringMethod(); if (baseToStringMethod is { IsSealed: true }) { if (baseToStringMethod.ContainingModule != this.ContainingModule && !this.DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureSealedToStringInRecord)) { var languageVersion = ((CSharpParseOptions)this.Locations[0].SourceTree!.Options).LanguageVersion; var requiredVersion = MessageID.IDS_FeatureSealedToStringInRecord.RequiredVersion(); diagnostics.Add( ErrorCode.ERR_InheritingFromRecordWithSealedToString, this.Locations[0], languageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } else { if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingToStringMethod)) { var toStringMethod = new SynthesizedRecordToString( this, printMethod, memberOffset: members.Count, isReadOnly: printMethod.IsEffectivelyReadOnly, diagnostics); members.Add(toStringMethod); } else { var toStringMethod = (MethodSymbol)existingToStringMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(toStringMethod, SpecialMember.System_Object__ToString, diagnostics) && toStringMethod.IsSealed && !IsSealed) { MessageID.IDS_FeatureSealedToStringInRecord.CheckFeatureAvailability( diagnostics, this.DeclaringCompilation, toStringMethod.Locations[0]); } } } MethodSymbol? getBaseToStringMethod() { var objectToString = this.DeclaringCompilation.GetSpecialTypeMember(SpecialMember.System_Object__ToString); var currentBaseType = this.BaseTypeNoUseSiteDiagnostics; while (currentBaseType is not null) { foreach (var member in currentBaseType.GetSimpleNonTypeMembers(WellKnownMemberNames.ObjectToString)) { if (member is not MethodSymbol method) continue; if (method.GetLeastOverriddenMethod(null) == objectToString) return method; } currentBaseType = currentBaseType.BaseTypeNoUseSiteDiagnostics; } return null; } } ImmutableArray<Symbol> addProperties(ImmutableArray<ParameterSymbol> recordParameters) { var existingOrAddedMembers = ArrayBuilder<Symbol>.GetInstance(recordParameters.Length); int addedCount = 0; foreach (ParameterSymbol param in recordParameters) { bool isInherited = false; var syntax = param.GetNonNullSyntaxNode(); var targetProperty = new SignatureOnlyPropertySymbol(param.Name, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); if (!memberSignatures.TryGetValue(targetProperty, out var existingMember) && !fieldsByName.TryGetValue(param.Name, out existingMember)) { existingMember = OverriddenOrHiddenMembersHelpers.FindFirstHiddenMemberIfAny(targetProperty, memberIsFromSomeCompilation: true); isInherited = true; } // There should be an error if we picked a member that is hidden // This will be fixed in C# 9 as part of 16.10. Tracked by https://github.com/dotnet/roslyn/issues/52630 if (existingMember is null) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: false, diagnostics)); } else if (existingMember is FieldSymbol { IsStatic: false } field && field.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { Binder.CheckFeatureAvailability(syntax, MessageID.IDS_FeaturePositionalFieldsInRecords, diagnostics); if (!isInherited || checkMemberNotHidden(field, param)) { existingOrAddedMembers.Add(field); } } else if (existingMember is PropertySymbol { IsStatic: false, GetMethod: { } } prop && prop.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { // There already exists a member corresponding to the candidate synthesized property. if (isInherited && prop.IsAbstract) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: true, diagnostics)); } else if (!isInherited || checkMemberNotHidden(prop, param)) { // Deconstruct() is specified to simply assign from this property to the corresponding out parameter. existingOrAddedMembers.Add(prop); } } else { diagnostics.Add(ErrorCode.ERR_BadRecordMemberForPositionalParameter, param.Locations[0], new FormattedSymbol(existingMember, SymbolDisplayFormat.CSharpErrorMessageFormat.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType)), param.TypeWithAnnotations, param.Name); } void addProperty(SynthesizedRecordPropertySymbol property) { existingOrAddedMembers.Add(property); members.Add(property); Debug.Assert(property.GetMethod is object); Debug.Assert(property.SetMethod is object); members.Add(property.GetMethod); members.Add(property.SetMethod); members.Add(property.BackingField); builder.AddInstanceInitializerForPositionalMembers(new FieldOrPropertyInitializer(property.BackingField, paramList.Parameters[param.Ordinal])); addedCount++; } } return existingOrAddedMembers.ToImmutableAndFree(); bool checkMemberNotHidden(Symbol symbol, ParameterSymbol param) { if (memberNames.Contains(symbol.Name) || this.GetTypeMembersDictionary().ContainsKey(symbol.Name)) { diagnostics.Add(ErrorCode.ERR_HiddenPositionalMember, param.Locations[0], symbol); return false; } return true; } } void addObjectEquals(MethodSymbol thisEquals) { members.Add(new SynthesizedRecordObjEquals(this, thisEquals, memberOffset: members.Count, diagnostics)); } MethodSymbol addGetHashCode(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectGetHashCode, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol getHashCode; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingHashCodeMethod)) { getHashCode = new SynthesizedRecordGetHashCode(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(getHashCode); } else { getHashCode = (MethodSymbol)existingHashCodeMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(getHashCode, SpecialMember.System_Object__GetHashCode, diagnostics) && getHashCode.IsSealed && !IsSealed) { diagnostics.Add(ErrorCode.ERR_SealedAPIInRecord, getHashCode.Locations[0], getHashCode); } } return getHashCode; } PropertySymbol addEqualityContract() { Debug.Assert(isRecordClass); var targetProperty = new SignatureOnlyPropertySymbol(SynthesizedRecordEqualityContractProperty.PropertyName, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Type)), ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); PropertySymbol equalityContract; if (!memberSignatures.TryGetValue(targetProperty, out Symbol? existingEqualityContractProperty)) { equalityContract = new SynthesizedRecordEqualityContractProperty(this, diagnostics); members.Add(equalityContract); members.Add(equalityContract.GetMethod); } else { equalityContract = (PropertySymbol)existingEqualityContractProperty; if (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { if (equalityContract.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, equalityContract.Locations[0], equalityContract); } } else if (equalityContract.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, equalityContract.Locations[0], equalityContract); } if (!equalityContract.Type.Equals(targetProperty.Type, TypeCompareKind.AllIgnoreOptions)) { if (!equalityContract.Type.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, equalityContract.Locations[0], equalityContract, targetProperty.Type); } } else { SynthesizedRecordEqualityContractProperty.VerifyOverridesEqualityContractFromBase(equalityContract, diagnostics); } if (equalityContract.GetMethod is null) { diagnostics.Add(ErrorCode.ERR_EqualityContractRequiresGetter, equalityContract.Locations[0], equalityContract); } reportStaticOrNotOverridableAPIInRecord(equalityContract, diagnostics); } return equalityContract; } MethodSymbol addThisEquals(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectEquals, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol thisEquals; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingEqualsMethod)) { thisEquals = new SynthesizedRecordEquals(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(thisEquals); } else { thisEquals = (MethodSymbol)existingEqualsMethod; if (thisEquals.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, thisEquals.Locations[0], thisEquals); } if (thisEquals.ReturnType.SpecialType != SpecialType.System_Boolean && !thisEquals.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, thisEquals.Locations[0], thisEquals, targetMethod.ReturnType); } reportStaticOrNotOverridableAPIInRecord(thisEquals, diagnostics); } return thisEquals; } void reportStaticOrNotOverridableAPIInRecord(Symbol symbol, BindingDiagnosticBag diagnostics) { if (isRecordClass && !IsSealed && ((!symbol.IsAbstract && !symbol.IsVirtual && !symbol.IsOverride) || symbol.IsSealed)) { diagnostics.Add(ErrorCode.ERR_NotOverridableAPIInRecord, symbol.Locations[0], symbol); } else if (symbol.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, symbol.Locations[0], symbol); } } void addBaseEquals() { Debug.Assert(isRecordClass); if (!BaseTypeNoUseSiteDiagnostics.IsObjectType()) { members.Add(new SynthesizedRecordBaseEquals(this, memberOffset: members.Count, diagnostics)); } } void addEqualityOperators() { members.Add(new SynthesizedRecordEqualityOperator(this, memberOffset: members.Count, diagnostics)); members.Add(new SynthesizedRecordInequalityOperator(this, memberOffset: members.Count, diagnostics)); } } private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { //we're not calling the helpers on NamedTypeSymbol base, because those call //GetMembers and we're inside a GetMembers call ourselves (i.e. stack overflow) var hasInstanceConstructor = false; var hasParameterlessInstanceConstructor = false; var hasStaticConstructor = false; // CONSIDER: if this traversal becomes a bottleneck, the flags could be made outputs of the // dictionary construction process. For now, this is more encapsulated. var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); foreach (var member in membersSoFar) { if (member.Kind == SymbolKind.Method) { var method = (MethodSymbol)member; switch (method.MethodKind) { case MethodKind.Constructor: // Ignore the record copy constructor if (!IsRecord || !(SynthesizedRecordCopyCtor.HasCopyConstructorSignature(method) && method is not SynthesizedRecordConstructor)) { hasInstanceConstructor = true; hasParameterlessInstanceConstructor = hasParameterlessInstanceConstructor || method.ParameterCount == 0; } break; case MethodKind.StaticConstructor: hasStaticConstructor = true; break; } } //kick out early if we've seen everything we're looking for if (hasInstanceConstructor && hasStaticConstructor) { break; } } // NOTE: Per section 11.3.8 of the spec, "every struct implicitly has a parameterless instance constructor". // We won't insert a parameterless constructor for a struct if there already is one. // The synthesized constructor will only be emitted if there are field initializers, but it should be in the symbol table. if ((!hasParameterlessInstanceConstructor && this.IsStructType()) || (!hasInstanceConstructor && !this.IsStatic && !this.IsInterface)) { builder.AddNonTypeMember((this.TypeKind == TypeKind.Submission) ? new SynthesizedSubmissionConstructor(this, diagnostics) : new SynthesizedInstanceConstructor(this), declaredMembersAndInitializers); } // constants don't count, since they do not exist as fields at runtime // NOTE: even for decimal constants (which require field initializers), // we do not create .cctor here since a static constructor implicitly created for a decimal // should not appear in the list returned by public API like GetMembers(). if (!hasStaticConstructor && hasNonConstantInitializer(declaredMembersAndInitializers.StaticInitializers)) { // Note: we don't have to put anything in the method - the binder will // do that when processing field initializers. builder.AddNonTypeMember(new SynthesizedStaticConstructor(this), declaredMembersAndInitializers); } if (this.IsScriptClass) { var scriptInitializer = new SynthesizedInteractiveInitializerMethod(this, diagnostics); builder.AddNonTypeMember(scriptInitializer, declaredMembersAndInitializers); var scriptEntryPoint = SynthesizedEntryPointSymbol.Create(scriptInitializer, diagnostics); builder.AddNonTypeMember(scriptEntryPoint, declaredMembersAndInitializers); } static bool hasNonConstantInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { return initializers.Any(siblings => siblings.Any(initializer => !initializer.FieldOpt.IsConst)); } } private void AddNonTypeMembers( DeclaredMembersAndInitializersBuilder builder, SyntaxList<MemberDeclarationSyntax> members, BindingDiagnosticBag diagnostics) { if (members.Count == 0) { return; } var firstMember = members[0]; var bodyBinder = this.GetBinder(firstMember); ArrayBuilder<FieldOrPropertyInitializer>? staticInitializers = null; ArrayBuilder<FieldOrPropertyInitializer>? instanceInitializers = null; var compilation = DeclaringCompilation; foreach (var m in members) { if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } bool reportMisplacedGlobalCode = !m.HasErrors; switch (m.Kind()) { case SyntaxKind.FieldDeclaration: { var fieldSyntax = (FieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(fieldSyntax.Declaration.Variables.First().Identifier)); } bool modifierErrors; var modifiers = SourceMemberFieldSymbol.MakeModifiers(this, fieldSyntax.Declaration.Variables[0].Identifier, fieldSyntax.Modifiers, diagnostics, out modifierErrors); foreach (var variable in fieldSyntax.Declaration.Variables) { var fieldSymbol = (modifiers & DeclarationModifiers.Fixed) == 0 ? new SourceMemberFieldSymbolFromDeclarator(this, variable, modifiers, modifierErrors, diagnostics) : new SourceFixedFieldSymbol(this, variable, modifiers, modifierErrors, diagnostics); builder.NonTypeMembers.Add(fieldSymbol); // All fields are included in the nullable context for constructors and initializers, even fields without // initializers, to ensure warnings are reported for uninitialized non-nullable fields in NullableWalker. builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: fieldSymbol.IsStatic, compilation, variable); if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, variable, this, DeclarationModifiers.Private | (modifiers & DeclarationModifiers.Static), fieldSymbol); } if (variable.Initializer != null) { if (fieldSymbol.IsStatic) { AddInitializer(ref staticInitializers, fieldSymbol, variable.Initializer); } else { AddInitializer(ref instanceInitializers, fieldSymbol, variable.Initializer); } } } } break; case SyntaxKind.MethodDeclaration: { var methodSyntax = (MethodDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(methodSyntax.Identifier)); } var method = SourceOrdinaryMethodSymbol.CreateMethodSymbol(this, bodyBinder, methodSyntax, compilation.IsNullableAnalysisEnabledIn(methodSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.ConstructorDeclaration: { var constructorSyntax = (ConstructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(constructorSyntax.Identifier)); } bool isNullableEnabled = compilation.IsNullableAnalysisEnabledIn(constructorSyntax); var constructor = SourceConstructorSymbol.CreateConstructorSymbol(this, constructorSyntax, isNullableEnabled, diagnostics); builder.NonTypeMembers.Add(constructor); if (constructorSyntax.Initializer?.Kind() != SyntaxKind.ThisConstructorInitializer) { builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: constructor.IsStatic, isNullableEnabled); } } break; case SyntaxKind.DestructorDeclaration: { var destructorSyntax = (DestructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(destructorSyntax.Identifier)); } // CONSIDER: if this doesn't (directly or indirectly) override object.Finalize, the // runtime won't consider it a finalizer and it will not be marked as a destructor // when it is loaded from metadata. Perhaps we should just treat it as an Ordinary // method in such cases? var destructor = new SourceDestructorSymbol(this, destructorSyntax, compilation.IsNullableAnalysisEnabledIn(destructorSyntax), diagnostics); builder.NonTypeMembers.Add(destructor); } break; case SyntaxKind.PropertyDeclaration: { var propertySyntax = (PropertyDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(propertySyntax.Identifier)); } var property = SourcePropertySymbol.Create(this, bodyBinder, propertySyntax, diagnostics); builder.NonTypeMembers.Add(property); AddAccessorIfAvailable(builder.NonTypeMembers, property.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, property.SetMethod); FieldSymbol backingField = property.BackingField; // TODO: can we leave this out of the member list? // From the 10/12/11 design notes: // In addition, we will change autoproperties to behavior in // a similar manner and make the autoproperty fields private. if ((object)backingField != null) { builder.NonTypeMembers.Add(backingField); builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: backingField.IsStatic, compilation, propertySyntax); var initializer = propertySyntax.Initializer; if (initializer != null) { if (IsScriptClass) { // also gather expression-declared variables from the initializer ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, initializer, this, DeclarationModifiers.Private | (property.IsStatic ? DeclarationModifiers.Static : 0), backingField); } if (property.IsStatic) { AddInitializer(ref staticInitializers, backingField, initializer); } else { AddInitializer(ref instanceInitializers, backingField, initializer); } } } } break; case SyntaxKind.EventFieldDeclaration: { var eventFieldSyntax = (EventFieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add( ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventFieldSyntax.Declaration.Variables.First().Identifier)); } foreach (VariableDeclaratorSyntax declarator in eventFieldSyntax.Declaration.Variables) { SourceFieldLikeEventSymbol @event = new SourceFieldLikeEventSymbol(this, bodyBinder, eventFieldSyntax.Modifiers, declarator, diagnostics); builder.NonTypeMembers.Add(@event); FieldSymbol? associatedField = @event.AssociatedField; if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, declarator, this, DeclarationModifiers.Private | (@event.IsStatic ? DeclarationModifiers.Static : 0), associatedField); } if ((object?)associatedField != null) { // NOTE: specifically don't add the associated field to the members list // (regard it as an implementation detail). builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: associatedField.IsStatic, compilation, declarator); if (declarator.Initializer != null) { if (associatedField.IsStatic) { AddInitializer(ref staticInitializers, associatedField, declarator.Initializer); } else { AddInitializer(ref instanceInitializers, associatedField, declarator.Initializer); } } } Debug.Assert((object)@event.AddMethod != null); Debug.Assert((object)@event.RemoveMethod != null); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); } } break; case SyntaxKind.EventDeclaration: { var eventSyntax = (EventDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventSyntax.Identifier)); } var @event = new SourceCustomEventSymbol(this, bodyBinder, eventSyntax, diagnostics); builder.NonTypeMembers.Add(@event); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); Debug.Assert(@event.AssociatedField is null); } break; case SyntaxKind.IndexerDeclaration: { var indexerSyntax = (IndexerDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(indexerSyntax.ThisKeyword)); } var indexer = SourcePropertySymbol.Create(this, bodyBinder, indexerSyntax, diagnostics); builder.HaveIndexers = true; builder.NonTypeMembers.Add(indexer); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.SetMethod); } break; case SyntaxKind.ConversionOperatorDeclaration: { var conversionOperatorSyntax = (ConversionOperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(conversionOperatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedConversionSymbol.CreateUserDefinedConversionSymbol( this, bodyBinder, conversionOperatorSyntax, compilation.IsNullableAnalysisEnabledIn(conversionOperatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.OperatorDeclaration: { var operatorSyntax = (OperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(operatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedOperatorSymbol.CreateUserDefinedOperatorSymbol( this, bodyBinder, operatorSyntax, compilation.IsNullableAnalysisEnabledIn(operatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.GlobalStatement: { var globalStatement = ((GlobalStatementSyntax)m).Statement; if (IsScriptClass) { var innerStatement = globalStatement; // drill into any LabeledStatements while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } switch (innerStatement.Kind()) { case SyntaxKind.LocalDeclarationStatement: // We shouldn't reach this place, but field declarations preceded with a label end up here. // This is tracked by https://github.com/dotnet/roslyn/issues/13712. Let's do our best for now. var decl = (LocalDeclarationStatementSyntax)innerStatement; foreach (var vdecl in decl.Declaration.Variables) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, vdecl, this, DeclarationModifiers.Private, containingFieldOpt: null); } break; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, innerStatement, this, DeclarationModifiers.Private, containingFieldOpt: null); break; default: // no other statement introduces variables into the enclosing scope break; } AddInitializer(ref instanceInitializers, null, globalStatement); } else if (reportMisplacedGlobalCode && !SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)m)) { diagnostics.Add(ErrorCode.ERR_GlobalStatement, new SourceLocation(globalStatement)); } } break; default: Debug.Assert( SyntaxFacts.IsTypeDeclaration(m.Kind()) || m.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration or SyntaxKind.IncompleteMember); break; } } AddInitializers(builder.InstanceInitializers, instanceInitializers); AddInitializers(builder.StaticInitializers, staticInitializers); } private void AddAccessorIfAvailable(ArrayBuilder<Symbol> symbols, MethodSymbol? accessorOpt) { if (!(accessorOpt is null)) { symbols.Add(accessorOpt); } } internal override byte? GetLocalNullableContextValue() { byte? value; if (!_flags.TryGetNullableContext(out value)) { value = ComputeNullableContextValue(); _flags.SetNullableContext(value); } return value; } private byte? ComputeNullableContextValue() { var compilation = DeclaringCompilation; if (!compilation.ShouldEmitNullableAttributes(this)) { return null; } var builder = new MostCommonNullableValueBuilder(); var baseType = BaseTypeNoUseSiteDiagnostics; if (baseType is object) { builder.AddValue(TypeWithAnnotations.Create(baseType)); } foreach (var @interface in GetInterfacesToEmit()) { builder.AddValue(TypeWithAnnotations.Create(@interface)); } foreach (var typeParameter in TypeParameters) { typeParameter.GetCommonNullableValues(compilation, ref builder); } foreach (var member in GetMembersUnordered()) { member.GetCommonNullableValues(compilation, ref builder); } // Not including lambdas or local functions. return builder.MostCommonValue; } /// <summary> /// Returns true if the overall nullable context is enabled for constructors and initializers. /// </summary> /// <param name="useStatic">Consider static constructor and fields rather than instance constructors and fields.</param> internal bool IsNullableEnabledForConstructorsAndInitializers(bool useStatic) { var membersAndInitializers = GetMembersAndInitializers(); return useStatic ? membersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields : membersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = DeclaringCompilation; NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics; if (baseType is object) { if (baseType.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(baseType, customModifiersCount: 0)); } if (baseType.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, baseType)); } if (baseType.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(baseType)); } } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out byte nullableContextValue)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue)); } if (baseType is object) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, nullableContextValue, TypeWithAnnotations.Create(baseType))); } } } #endregion #region Extension Methods internal bool ContainsExtensionMethods { get { if (!_lazyContainsExtensionMethods.HasValue()) { bool containsExtensionMethods = ((this.IsStatic && !this.IsGenericType) || this.IsScriptClass) && this.declaration.ContainsExtensionMethods; _lazyContainsExtensionMethods = containsExtensionMethods.ToThreeState(); } return _lazyContainsExtensionMethods.Value(); } } internal bool AnyMemberHasAttributes { get { if (!_lazyAnyMemberHasAttributes.HasValue()) { bool anyMemberHasAttributes = this.declaration.AnyMemberHasAttributes; _lazyAnyMemberHasAttributes = anyMemberHasAttributes.ToThreeState(); } return _lazyAnyMemberHasAttributes.Value(); } } public override bool MightContainExtensionMethods { get { return this.ContainsExtensionMethods; } } #endregion public sealed override NamedTypeSymbol ConstructedFrom { get { return this; } } internal sealed override bool HasFieldInitializers() => InstanceInitializers.Length > 0; internal class SynthesizedExplicitImplementations { public static readonly SynthesizedExplicitImplementations Empty = new SynthesizedExplicitImplementations(ImmutableArray<SynthesizedExplicitImplementationForwardingMethod>.Empty, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)>.Empty); public readonly ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> ForwardingMethods; public readonly ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> MethodImpls; private SynthesizedExplicitImplementations( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { ForwardingMethods = forwardingMethods.NullToEmpty(); MethodImpls = methodImpls.NullToEmpty(); } internal static SynthesizedExplicitImplementations Create( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { if (forwardingMethods.IsDefaultOrEmpty && methodImpls.IsDefaultOrEmpty) { return Empty; } return new SynthesizedExplicitImplementations(forwardingMethods, methodImpls); } } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SourceOrdinaryMethodSymbol : SourceOrdinaryMethodSymbolBase { private readonly TypeSymbol _explicitInterfaceType; private readonly bool _isExpressionBodied; private readonly bool _hasAnyBody; private readonly RefKind _refKind; private bool _lazyIsVararg; /// <summary> /// A collection of type parameter constraint types, populated when /// constraint types for the first type parameter is requested. /// Initialized in two steps. Hold a copy if accessing during initialization. /// </summary> private ImmutableArray<ImmutableArray<TypeWithAnnotations>> _lazyTypeParameterConstraintTypes; /// <summary> /// A collection of type parameter constraint kinds, populated when /// constraint kinds for the first type parameter is requested. /// Initialized in two steps. Hold a copy if accessing during initialization. /// </summary> private ImmutableArray<TypeParameterConstraintKind> _lazyTypeParameterConstraintKinds; /// <summary> /// If this symbol represents a partial method definition or implementation part, its other part (if any). /// This should be set, if at all, before this symbol appears among the members of its owner. /// The implementation part is not listed among the "members" of the enclosing type. /// </summary> private SourceOrdinaryMethodSymbol _otherPartOfPartial; public static SourceOrdinaryMethodSymbol CreateMethodSymbol( NamedTypeSymbol containingType, Binder bodyBinder, MethodDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) { var interfaceSpecifier = syntax.ExplicitInterfaceSpecifier; var nameToken = syntax.Identifier; TypeSymbol explicitInterfaceType; var name = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(bodyBinder, interfaceSpecifier, nameToken.ValueText, diagnostics, out explicitInterfaceType, aliasQualifierOpt: out _); var location = new SourceLocation(nameToken); var methodKind = interfaceSpecifier == null ? MethodKind.Ordinary : MethodKind.ExplicitInterfaceImplementation; return new SourceOrdinaryMethodSymbol(containingType, explicitInterfaceType, name, location, syntax, methodKind, isNullableAnalysisEnabled, diagnostics); } private SourceOrdinaryMethodSymbol( NamedTypeSymbol containingType, TypeSymbol explicitInterfaceType, string name, Location location, MethodDeclarationSyntax syntax, MethodKind methodKind, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, name, location, syntax, methodKind, isIterator: SyntaxFacts.HasYieldOperations(syntax.Body), isExtensionMethod: syntax.ParameterList.Parameters.FirstOrDefault() is ParameterSyntax firstParam && !firstParam.IsArgList && firstParam.Modifiers.Any(SyntaxKind.ThisKeyword), isPartial: syntax.Modifiers.IndexOf(SyntaxKind.PartialKeyword) < 0, hasBody: syntax.Body != null || syntax.ExpressionBody != null, isNullableAnalysisEnabled: isNullableAnalysisEnabled, diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); _explicitInterfaceType = explicitInterfaceType; bool hasBlockBody = syntax.Body != null; _isExpressionBodied = !hasBlockBody && syntax.ExpressionBody != null; bool hasBody = hasBlockBody || _isExpressionBodied; _hasAnyBody = hasBody; _refKind = syntax.ReturnType.GetRefKind(); CheckForBlockAndExpressionBody( syntax.Body, syntax.ExpressionBody, syntax, diagnostics); } protected override ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { var syntax = (MethodDeclarationSyntax)node; if (syntax.Arity == 0) { ReportErrorIfHasConstraints(syntax.ConstraintClauses, diagnostics.DiagnosticBag); return ImmutableArray<TypeParameterSymbol>.Empty; } else { return MakeTypeParameters(syntax, diagnostics); } } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); var withTypeParamsBinder = this.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax.ReturnType, syntax, this); SyntaxToken arglistToken; // Constraint checking for parameter and return types must be delayed until // the method has been added to the containing type member list since // evaluating the constraints may depend on accessing this method from // the container (comparing this method to others to find overrides for // instance). Constraints are checked in AfterAddingTypeMembersChecks. var signatureBinder = withTypeParamsBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); ImmutableArray<ParameterSymbol> parameters = ParameterHelpers.MakeParameters( signatureBinder, this, syntax.ParameterList, out arglistToken, allowRefOrOut: true, allowThis: true, addRefReadOnlyModifier: IsVirtual || IsAbstract, diagnostics: diagnostics); _lazyIsVararg = (arglistToken.Kind() == SyntaxKind.ArgListKeyword); RefKind refKind; var returnTypeSyntax = syntax.ReturnType.SkipRef(out refKind); TypeWithAnnotations returnType = signatureBinder.BindType(returnTypeSyntax, diagnostics); // span-like types are returnable in general if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true)) { if (returnType.SpecialType == SpecialType.System_TypedReference && (this.ContainingType.SpecialType == SpecialType.System_TypedReference || this.ContainingType.SpecialType == SpecialType.System_ArgIterator)) { // Two special cases: methods in the special types TypedReference and ArgIterator are allowed to return TypedReference } else { // The return type of a method, delegate, or function pointer cannot be '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, syntax.ReturnType.Location, returnType.Type); } } Debug.Assert(this.RefKind == RefKind.None || !returnType.IsVoidType() || returnTypeSyntax.HasErrors); ImmutableArray<TypeParameterConstraintClause> declaredConstraints = default; if (this.Arity != 0 && (syntax.ExplicitInterfaceSpecifier != null || IsOverride)) { // When a generic method overrides a generic method declared in a base class, or is an // explicit interface member implementation of a method in a base interface, the method // shall not specify any type-parameter-constraints-clauses, except for a struct, class, or default constraint. // In these cases, the type parameters of the method inherit constraints from the method being overridden or // implemented. if (syntax.ConstraintClauses.Count > 0) { Binder.CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_OverrideWithConstraints, diagnostics, syntax.ConstraintClauses[0].WhereKeyword.GetLocation()); declaredConstraints = signatureBinder.WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks). BindTypeParameterConstraintClauses(this, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, diagnostics, performOnlyCycleSafeValidation: false, isForOverride: true); Debug.Assert(declaredConstraints.All(clause => clause.ConstraintTypes.IsEmpty)); } // Force resolution of nullable type parameter used in the signature of an override or explicit interface implementation // based on constraints specified by the declaration. foreach (var param in parameters) { forceMethodTypeParameters(param.TypeWithAnnotations, this, declaredConstraints); } forceMethodTypeParameters(returnType, this, declaredConstraints); } return (returnType, parameters, _lazyIsVararg, declaredConstraints); static void forceMethodTypeParameters(TypeWithAnnotations type, SourceOrdinaryMethodSymbol method, ImmutableArray<TypeParameterConstraintClause> declaredConstraints) { type.VisitType(null, (type, args, unused2) => { if (type.DefaultType is TypeParameterSymbol typeParameterSymbol && typeParameterSymbol.DeclaringMethod == (object)args.method) { var asValueType = args.declaredConstraints.IsDefault || (args.declaredConstraints[typeParameterSymbol.Ordinal].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.Default)) == 0; type.TryForceResolve(asValueType); } return false; }, typePredicate: null, arg: (method, declaredConstraints), canDigThroughNullable: false, useDefaultType: true); } } protected override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) { // errors relevant for extension methods if (IsExtensionMethod) { var syntax = GetSyntax(); var location = locations[0]; var parameter0Type = this.Parameters[0].TypeWithAnnotations; var parameter0RefKind = this.Parameters[0].RefKind; if (!parameter0Type.Type.IsValidExtensionParameterType()) { // Duplicate Dev10 behavior by selecting the parameter type. var parameterSyntax = syntax.ParameterList.Parameters[0]; Debug.Assert(parameterSyntax.Type != null); var loc = parameterSyntax.Type.Location; diagnostics.Add(ErrorCode.ERR_BadTypeforThis, loc, parameter0Type.Type); } else if (parameter0RefKind == RefKind.Ref && !parameter0Type.Type.IsValueType) { diagnostics.Add(ErrorCode.ERR_RefExtensionMustBeValueTypeOrConstrainedToOne, location, Name); } else if (parameter0RefKind == RefKind.In && parameter0Type.TypeKind != TypeKind.Struct) { diagnostics.Add(ErrorCode.ERR_InExtensionMustBeValueType, location, Name); } else if ((object)ContainingType.ContainingType != null) { diagnostics.Add(ErrorCode.ERR_ExtensionMethodsDecl, location, ContainingType.Name); } else if (!ContainingType.IsScriptClass && !(ContainingType.IsStatic && ContainingType.Arity == 0)) { // Duplicate Dev10 behavior by selecting the containing type identifier. However if there // is no containing type (in the interactive case for instance), select the method identifier. var typeDecl = syntax.Parent as TypeDeclarationSyntax; var identifier = (typeDecl != null) ? typeDecl.Identifier : syntax.Identifier; var loc = identifier.GetLocation(); diagnostics.Add(ErrorCode.ERR_BadExtensionAgg, loc); } else if (!IsStatic) { diagnostics.Add(ErrorCode.ERR_BadExtensionMeth, location); } else { // Verify ExtensionAttribute is available. var attributeConstructor = Binder.GetWellKnownTypeMember(DeclaringCompilation, WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor, out var useSiteInfo); Location thisLocation = syntax.ParameterList.Parameters[0].Modifiers.FirstOrDefault(SyntaxKind.ThisKeyword).GetLocation(); if ((object)attributeConstructor == null) { var memberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor); // do not use Binder.ReportUseSiteErrorForAttributeCtor in this case, because we'll need to report a special error id, not a generic use site error. diagnostics.Add( ErrorCode.ERR_ExtensionAttrNotFound, thisLocation, memberDescriptor.DeclaringTypeMetadataName); } else { diagnostics.Add(useSiteInfo, thisLocation); } } } } protected override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); return this.FindExplicitlyImplementedMethod(isOperator: false, _explicitInterfaceType, syntax.Identifier.ValueText, syntax.ExplicitInterfaceSpecifier, diagnostics); } protected override Location ReturnTypeLocation => GetSyntax().ReturnType.Location; protected override TypeSymbol ExplicitInterfaceType => _explicitInterfaceType; protected override bool HasAnyBody => _hasAnyBody; internal MethodDeclarationSyntax GetSyntax() { Debug.Assert(syntaxReferenceOpt != null); return (MethodDeclarationSyntax)syntaxReferenceOpt.GetSyntax(); } protected override void CompleteAsyncMethodChecksBetweenStartAndFinish() { if (IsPartialDefinition) { DeclaringCompilation.SymbolDeclaredEvent(this); } } public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() { if (_lazyTypeParameterConstraintTypes.IsDefault) { GetTypeParameterConstraintKinds(); var diagnostics = BindingDiagnosticBag.GetInstance(); var syntax = GetSyntax(); var withTypeParametersBinder = this.DeclaringCompilation .GetBinderFactory(syntax.SyntaxTree) .GetBinder(syntax.ReturnType, syntax, this); var constraints = this.MakeTypeParameterConstraintTypes( withTypeParametersBinder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintTypes, constraints)) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _lazyTypeParameterConstraintTypes; } public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() { if (_lazyTypeParameterConstraintKinds.IsDefault) { var syntax = GetSyntax(); var withTypeParametersBinder = this.DeclaringCompilation .GetBinderFactory(syntax.SyntaxTree) .GetBinder(syntax.ReturnType, syntax, this); var constraints = this.MakeTypeParameterConstraintKinds( withTypeParametersBinder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses); ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, constraints); } return _lazyTypeParameterConstraintKinds; } public override bool IsVararg { get { LazyMethodChecks(); return _lazyIsVararg; } } protected override int GetParameterCountFromSyntax() => GetSyntax().ParameterList.ParameterCount; public override RefKind RefKind { get { return _refKind; } } internal static void InitializePartialMethodParts(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation) { Debug.Assert(definition.IsPartialDefinition); Debug.Assert(implementation.IsPartialImplementation); Debug.Assert((object)definition._otherPartOfPartial == null || (object)definition._otherPartOfPartial == implementation); Debug.Assert((object)implementation._otherPartOfPartial == null || (object)implementation._otherPartOfPartial == definition); definition._otherPartOfPartial = implementation; implementation._otherPartOfPartial = definition; } /// <summary> /// If this is a partial implementation part returns the definition part and vice versa. /// </summary> internal SourceOrdinaryMethodSymbol OtherPartOfPartial { get { return _otherPartOfPartial; } } /// <summary> /// Returns true if this symbol represents a partial method definition (the part that specifies a signature but no body). /// </summary> internal bool IsPartialDefinition { get { return this.IsPartial && !_hasAnyBody && !HasExternModifier; } } /// <summary> /// Returns true if this symbol represents a partial method implementation (the part that specifies both signature and body). /// </summary> internal bool IsPartialImplementation { get { return this.IsPartial && (_hasAnyBody || HasExternModifier); } } /// <summary> /// True if this is a partial method that doesn't have an implementation part. /// </summary> internal bool IsPartialWithoutImplementation { get { return this.IsPartialDefinition && (object)_otherPartOfPartial == null; } } /// <summary> /// Returns the implementation part of a partial method definition, /// or null if this is not a partial method or it is the definition part. /// </summary> internal SourceOrdinaryMethodSymbol SourcePartialDefinition { get { return this.IsPartialImplementation ? _otherPartOfPartial : null; } } /// <summary> /// Returns the definition part of a partial method implementation, /// or null if this is not a partial method or it is the implementation part. /// </summary> internal SourceOrdinaryMethodSymbol SourcePartialImplementation { get { return this.IsPartialDefinition ? _otherPartOfPartial : null; } } public override MethodSymbol PartialDefinitionPart { get { return SourcePartialDefinition; } } public override MethodSymbol PartialImplementationPart { get { return SourcePartialImplementation; } } public sealed override bool IsExtern { get { return IsPartialDefinition ? _otherPartOfPartial?.IsExtern ?? false : HasExternModifier; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { ref var lazyDocComment = ref expandIncludes ? ref this.lazyExpandedDocComment : ref this.lazyDocComment; return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(SourcePartialImplementation ?? this, expandIncludes, ref lazyDocComment); } protected override SourceMemberMethodSymbol BoundAttributesSource { get { return this.SourcePartialDefinition; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { if ((object)this.SourcePartialImplementation != null) { return OneOrMany.Create(ImmutableArray.Create(AttributeDeclarationSyntaxList, this.SourcePartialImplementation.AttributeDeclarationSyntaxList)); } else { return OneOrMany.Create(AttributeDeclarationSyntaxList); } } private SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList { get { var sourceContainer = this.ContainingType as SourceMemberContainerTypeSymbol; if ((object)sourceContainer != null && sourceContainer.AnyMemberHasAttributes) { return this.GetSyntax().AttributeLists; } return default(SyntaxList<AttributeListSyntax>); } } internal override bool IsExpressionBodied { get { return _isExpressionBodied; } } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); return ModifierUtils.MakeAndCheckNontypeMemberModifiers(syntax.Modifiers, defaultAccess: DeclarationModifiers.None, allowedModifiers, Locations[0], diagnostics, out _); } private ImmutableArray<TypeParameterSymbol> MakeTypeParameters(MethodDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax.TypeParameterList != null); OverriddenMethodTypeParameterMapBase typeMap = null; if (this.IsOverride) { typeMap = new OverriddenMethodTypeParameterMap(this); } else if (this.IsExplicitInterfaceImplementation) { typeMap = new ExplicitInterfaceMethodTypeParameterMap(this); } var typeParameters = syntax.TypeParameterList.Parameters; var result = ArrayBuilder<TypeParameterSymbol>.GetInstance(); for (int ordinal = 0; ordinal < typeParameters.Count; ordinal++) { var parameter = typeParameters[ordinal]; if (parameter.VarianceKeyword.Kind() != SyntaxKind.None) { diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, parameter.VarianceKeyword.GetLocation()); } var identifier = parameter.Identifier; var location = identifier.GetLocation(); var name = identifier.ValueText; // Note: It is not an error to have a type parameter named the same as its enclosing method: void M<M>() {} for (int i = 0; i < result.Count; i++) { if (name == result[i].Name) { diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, name); break; } } SourceMemberContainerTypeSymbol.ReportTypeNamedRecord(identifier.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, location); var tpEnclosing = ContainingType.FindEnclosingTypeParameter(name); if ((object)tpEnclosing != null) { // Type parameter '{0}' has the same name as the type parameter from outer type '{1}' diagnostics.Add(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, location, name, tpEnclosing.ContainingType); } var syntaxRefs = ImmutableArray.Create(parameter.GetReference()); var locations = ImmutableArray.Create(location); var typeParameter = (typeMap != null) ? (TypeParameterSymbol)new SourceOverridingMethodTypeParameterSymbol( typeMap, name, ordinal, locations, syntaxRefs) : new SourceMethodTypeParameterSymbol( this, name, ordinal, locations, syntaxRefs); result.Add(typeParameter); } return result.ToImmutableAndFree(); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { var implementingPart = this.SourcePartialImplementation; if ((object)implementingPart != null) { implementingPart.ForceComplete(locationOpt, cancellationToken); } base.ForceComplete(locationOpt, cancellationToken); } internal override bool IsDefinedInSourceTree( SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { // Since only the declaring (and not the implementing) part of a partial method appears in the member // list, we need to ensure we complete the implementation part when needed. return base.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) || this.SourcePartialImplementation?.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) == true; } protected override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { if ((object)_explicitInterfaceType != null) { var syntax = this.GetSyntax(); Debug.Assert(syntax.ExplicitInterfaceSpecifier != null); _explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, new SourceLocation(syntax.ExplicitInterfaceSpecifier.Name), diagnostics); } } protected override void PartialMethodChecks(BindingDiagnosticBag diagnostics) { var implementingPart = this.SourcePartialImplementation; if ((object)implementingPart != null) { PartialMethodChecks(this, implementingPart, diagnostics); } } /// <summary> /// Report differences between the defining and implementing /// parts of a partial method. Diagnostics are reported on the /// implementing part, matching Dev10 behavior. /// </summary> private static void PartialMethodChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(definition, implementation)); MethodSymbol constructedDefinition = definition.ConstructIfGeneric(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementation.TypeParameters)); bool hasTypeDifferences = !constructedDefinition.ReturnTypeWithAnnotations.Equals(implementation.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); if (hasTypeDifferences) { diagnostics.Add(ErrorCode.ERR_PartialMethodReturnTypeDifference, implementation.Locations[0]); } else if (MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(definition, implementation)) { hasTypeDifferences = true; diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentTupleNames, implementation.Locations[0], definition, implementation); } if (definition.RefKind != implementation.RefKind) { diagnostics.Add(ErrorCode.ERR_PartialMethodRefReturnDifference, implementation.Locations[0]); } if (definition.IsStatic != implementation.IsStatic) { diagnostics.Add(ErrorCode.ERR_PartialMethodStaticDifference, implementation.Locations[0]); } if (definition.IsDeclaredReadOnly != implementation.IsDeclaredReadOnly) { diagnostics.Add(ErrorCode.ERR_PartialMethodReadOnlyDifference, implementation.Locations[0]); } if (definition.IsExtensionMethod != implementation.IsExtensionMethod) { diagnostics.Add(ErrorCode.ERR_PartialMethodExtensionDifference, implementation.Locations[0]); } if (definition.IsUnsafe != implementation.IsUnsafe && definition.CompilationAllowsUnsafe()) // Don't cascade. { diagnostics.Add(ErrorCode.ERR_PartialMethodUnsafeDifference, implementation.Locations[0]); } if (definition.IsParams() != implementation.IsParams()) { diagnostics.Add(ErrorCode.ERR_PartialMethodParamsDifference, implementation.Locations[0]); } if (definition.HasExplicitAccessModifier != implementation.HasExplicitAccessModifier || definition.DeclaredAccessibility != implementation.DeclaredAccessibility) { diagnostics.Add(ErrorCode.ERR_PartialMethodAccessibilityDifference, implementation.Locations[0]); } if (definition.IsVirtual != implementation.IsVirtual || definition.IsOverride != implementation.IsOverride || definition.IsSealed != implementation.IsSealed || definition.IsNew != implementation.IsNew) { diagnostics.Add(ErrorCode.ERR_PartialMethodExtendedModDifference, implementation.Locations[0]); } PartialMethodConstraintsChecks(definition, implementation, diagnostics); if (SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( implementation.DeclaringCompilation, constructedDefinition, implementation, diagnostics, static (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { // report only if this is an unsafe *nullability* difference diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial, implementingMethod.Locations[0]); }, static (diagnostics, implementedMethod, implementingMethod, implementingParameter, blameAttributes, arg) => { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat)); }, extraArgument: (object)null)) { hasTypeDifferences = true; } if ((!hasTypeDifferences && !MemberSignatureComparer.PartialMethodsStrictComparer.Equals(definition, implementation)) || hasDifferencesInParameterOrTypeParameterName(definition, implementation)) { diagnostics.Add(ErrorCode.WRN_PartialMethodTypeDifference, implementation.Locations[0], new FormattedSymbol(definition, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementation, SymbolDisplayFormat.MinimallyQualifiedFormat)); } static bool hasDifferencesInParameterOrTypeParameterName(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation) { return !definition.Parameters.SequenceEqual(implementation.Parameters, (a, b) => a.Name == b.Name) || !definition.TypeParameters.SequenceEqual(implementation.TypeParameters, (a, b) => a.Name == b.Name); } } private static void PartialMethodConstraintsChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(definition, implementation)); Debug.Assert(definition.Arity == implementation.Arity); var typeParameters1 = definition.TypeParameters; int arity = typeParameters1.Length; if (arity == 0) { return; } var typeParameters2 = implementation.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentConstraints, implementation.Locations[0], implementation, typeParameter2.Name); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, implementation.Locations[0], implementation, typeParameter2.Name); } } } internal override bool CallsAreOmitted(SyntaxTree syntaxTree) { if (this.IsPartialWithoutImplementation) { return true; } return base.CallsAreOmitted(syntaxTree); } internal override bool GenerateDebugInfo => !IsAsync && !IsIterator; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SourceOrdinaryMethodSymbol : SourceOrdinaryMethodSymbolBase { private readonly TypeSymbol _explicitInterfaceType; private readonly bool _isExpressionBodied; private readonly bool _hasAnyBody; private readonly RefKind _refKind; private bool _lazyIsVararg; /// <summary> /// A collection of type parameter constraint types, populated when /// constraint types for the first type parameter is requested. /// Initialized in two steps. Hold a copy if accessing during initialization. /// </summary> private ImmutableArray<ImmutableArray<TypeWithAnnotations>> _lazyTypeParameterConstraintTypes; /// <summary> /// A collection of type parameter constraint kinds, populated when /// constraint kinds for the first type parameter is requested. /// Initialized in two steps. Hold a copy if accessing during initialization. /// </summary> private ImmutableArray<TypeParameterConstraintKind> _lazyTypeParameterConstraintKinds; /// <summary> /// If this symbol represents a partial method definition or implementation part, its other part (if any). /// This should be set, if at all, before this symbol appears among the members of its owner. /// The implementation part is not listed among the "members" of the enclosing type. /// </summary> private SourceOrdinaryMethodSymbol _otherPartOfPartial; public static SourceOrdinaryMethodSymbol CreateMethodSymbol( NamedTypeSymbol containingType, Binder bodyBinder, MethodDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) { var interfaceSpecifier = syntax.ExplicitInterfaceSpecifier; var nameToken = syntax.Identifier; TypeSymbol explicitInterfaceType; var name = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(bodyBinder, interfaceSpecifier, nameToken.ValueText, diagnostics, out explicitInterfaceType, aliasQualifierOpt: out _); var location = new SourceLocation(nameToken); var methodKind = interfaceSpecifier == null ? MethodKind.Ordinary : MethodKind.ExplicitInterfaceImplementation; return new SourceOrdinaryMethodSymbol(containingType, explicitInterfaceType, name, location, syntax, methodKind, isNullableAnalysisEnabled, diagnostics); } private SourceOrdinaryMethodSymbol( NamedTypeSymbol containingType, TypeSymbol explicitInterfaceType, string name, Location location, MethodDeclarationSyntax syntax, MethodKind methodKind, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, name, location, syntax, methodKind, isIterator: SyntaxFacts.HasYieldOperations(syntax.Body), isExtensionMethod: syntax.ParameterList.Parameters.FirstOrDefault() is ParameterSyntax firstParam && !firstParam.IsArgList && firstParam.Modifiers.Any(SyntaxKind.ThisKeyword), isPartial: syntax.Modifiers.IndexOf(SyntaxKind.PartialKeyword) < 0, isReadOnly: false, hasBody: syntax.Body != null || syntax.ExpressionBody != null, isNullableAnalysisEnabled: isNullableAnalysisEnabled, diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); _explicitInterfaceType = explicitInterfaceType; bool hasBlockBody = syntax.Body != null; _isExpressionBodied = !hasBlockBody && syntax.ExpressionBody != null; bool hasBody = hasBlockBody || _isExpressionBodied; _hasAnyBody = hasBody; _refKind = syntax.ReturnType.GetRefKind(); CheckForBlockAndExpressionBody( syntax.Body, syntax.ExpressionBody, syntax, diagnostics); } protected override ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { var syntax = (MethodDeclarationSyntax)node; if (syntax.Arity == 0) { ReportErrorIfHasConstraints(syntax.ConstraintClauses, diagnostics.DiagnosticBag); return ImmutableArray<TypeParameterSymbol>.Empty; } else { return MakeTypeParameters(syntax, diagnostics); } } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); var withTypeParamsBinder = this.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax.ReturnType, syntax, this); SyntaxToken arglistToken; // Constraint checking for parameter and return types must be delayed until // the method has been added to the containing type member list since // evaluating the constraints may depend on accessing this method from // the container (comparing this method to others to find overrides for // instance). Constraints are checked in AfterAddingTypeMembersChecks. var signatureBinder = withTypeParamsBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); ImmutableArray<ParameterSymbol> parameters = ParameterHelpers.MakeParameters( signatureBinder, this, syntax.ParameterList, out arglistToken, allowRefOrOut: true, allowThis: true, addRefReadOnlyModifier: IsVirtual || IsAbstract, diagnostics: diagnostics); _lazyIsVararg = (arglistToken.Kind() == SyntaxKind.ArgListKeyword); RefKind refKind; var returnTypeSyntax = syntax.ReturnType.SkipRef(out refKind); TypeWithAnnotations returnType = signatureBinder.BindType(returnTypeSyntax, diagnostics); // span-like types are returnable in general if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true)) { if (returnType.SpecialType == SpecialType.System_TypedReference && (this.ContainingType.SpecialType == SpecialType.System_TypedReference || this.ContainingType.SpecialType == SpecialType.System_ArgIterator)) { // Two special cases: methods in the special types TypedReference and ArgIterator are allowed to return TypedReference } else { // The return type of a method, delegate, or function pointer cannot be '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, syntax.ReturnType.Location, returnType.Type); } } Debug.Assert(this.RefKind == RefKind.None || !returnType.IsVoidType() || returnTypeSyntax.HasErrors); ImmutableArray<TypeParameterConstraintClause> declaredConstraints = default; if (this.Arity != 0 && (syntax.ExplicitInterfaceSpecifier != null || IsOverride)) { // When a generic method overrides a generic method declared in a base class, or is an // explicit interface member implementation of a method in a base interface, the method // shall not specify any type-parameter-constraints-clauses, except for a struct, class, or default constraint. // In these cases, the type parameters of the method inherit constraints from the method being overridden or // implemented. if (syntax.ConstraintClauses.Count > 0) { Binder.CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_OverrideWithConstraints, diagnostics, syntax.ConstraintClauses[0].WhereKeyword.GetLocation()); declaredConstraints = signatureBinder.WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks). BindTypeParameterConstraintClauses(this, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, diagnostics, performOnlyCycleSafeValidation: false, isForOverride: true); Debug.Assert(declaredConstraints.All(clause => clause.ConstraintTypes.IsEmpty)); } // Force resolution of nullable type parameter used in the signature of an override or explicit interface implementation // based on constraints specified by the declaration. foreach (var param in parameters) { forceMethodTypeParameters(param.TypeWithAnnotations, this, declaredConstraints); } forceMethodTypeParameters(returnType, this, declaredConstraints); } return (returnType, parameters, _lazyIsVararg, declaredConstraints); static void forceMethodTypeParameters(TypeWithAnnotations type, SourceOrdinaryMethodSymbol method, ImmutableArray<TypeParameterConstraintClause> declaredConstraints) { type.VisitType(null, (type, args, unused2) => { if (type.DefaultType is TypeParameterSymbol typeParameterSymbol && typeParameterSymbol.DeclaringMethod == (object)args.method) { var asValueType = args.declaredConstraints.IsDefault || (args.declaredConstraints[typeParameterSymbol.Ordinal].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.Default)) == 0; type.TryForceResolve(asValueType); } return false; }, typePredicate: null, arg: (method, declaredConstraints), canDigThroughNullable: false, useDefaultType: true); } } protected override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) { // errors relevant for extension methods if (IsExtensionMethod) { var syntax = GetSyntax(); var location = locations[0]; var parameter0Type = this.Parameters[0].TypeWithAnnotations; var parameter0RefKind = this.Parameters[0].RefKind; if (!parameter0Type.Type.IsValidExtensionParameterType()) { // Duplicate Dev10 behavior by selecting the parameter type. var parameterSyntax = syntax.ParameterList.Parameters[0]; Debug.Assert(parameterSyntax.Type != null); var loc = parameterSyntax.Type.Location; diagnostics.Add(ErrorCode.ERR_BadTypeforThis, loc, parameter0Type.Type); } else if (parameter0RefKind == RefKind.Ref && !parameter0Type.Type.IsValueType) { diagnostics.Add(ErrorCode.ERR_RefExtensionMustBeValueTypeOrConstrainedToOne, location, Name); } else if (parameter0RefKind == RefKind.In && parameter0Type.TypeKind != TypeKind.Struct) { diagnostics.Add(ErrorCode.ERR_InExtensionMustBeValueType, location, Name); } else if ((object)ContainingType.ContainingType != null) { diagnostics.Add(ErrorCode.ERR_ExtensionMethodsDecl, location, ContainingType.Name); } else if (!ContainingType.IsScriptClass && !(ContainingType.IsStatic && ContainingType.Arity == 0)) { // Duplicate Dev10 behavior by selecting the containing type identifier. However if there // is no containing type (in the interactive case for instance), select the method identifier. var typeDecl = syntax.Parent as TypeDeclarationSyntax; var identifier = (typeDecl != null) ? typeDecl.Identifier : syntax.Identifier; var loc = identifier.GetLocation(); diagnostics.Add(ErrorCode.ERR_BadExtensionAgg, loc); } else if (!IsStatic) { diagnostics.Add(ErrorCode.ERR_BadExtensionMeth, location); } else { // Verify ExtensionAttribute is available. var attributeConstructor = Binder.GetWellKnownTypeMember(DeclaringCompilation, WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor, out var useSiteInfo); Location thisLocation = syntax.ParameterList.Parameters[0].Modifiers.FirstOrDefault(SyntaxKind.ThisKeyword).GetLocation(); if ((object)attributeConstructor == null) { var memberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor); // do not use Binder.ReportUseSiteErrorForAttributeCtor in this case, because we'll need to report a special error id, not a generic use site error. diagnostics.Add( ErrorCode.ERR_ExtensionAttrNotFound, thisLocation, memberDescriptor.DeclaringTypeMetadataName); } else { diagnostics.Add(useSiteInfo, thisLocation); } } } } protected override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); return this.FindExplicitlyImplementedMethod(isOperator: false, _explicitInterfaceType, syntax.Identifier.ValueText, syntax.ExplicitInterfaceSpecifier, diagnostics); } protected override Location ReturnTypeLocation => GetSyntax().ReturnType.Location; protected override TypeSymbol ExplicitInterfaceType => _explicitInterfaceType; protected override bool HasAnyBody => _hasAnyBody; internal MethodDeclarationSyntax GetSyntax() { Debug.Assert(syntaxReferenceOpt != null); return (MethodDeclarationSyntax)syntaxReferenceOpt.GetSyntax(); } protected override void CompleteAsyncMethodChecksBetweenStartAndFinish() { if (IsPartialDefinition) { DeclaringCompilation.SymbolDeclaredEvent(this); } } public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() { if (_lazyTypeParameterConstraintTypes.IsDefault) { GetTypeParameterConstraintKinds(); var diagnostics = BindingDiagnosticBag.GetInstance(); var syntax = GetSyntax(); var withTypeParametersBinder = this.DeclaringCompilation .GetBinderFactory(syntax.SyntaxTree) .GetBinder(syntax.ReturnType, syntax, this); var constraints = this.MakeTypeParameterConstraintTypes( withTypeParametersBinder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintTypes, constraints)) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _lazyTypeParameterConstraintTypes; } public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() { if (_lazyTypeParameterConstraintKinds.IsDefault) { var syntax = GetSyntax(); var withTypeParametersBinder = this.DeclaringCompilation .GetBinderFactory(syntax.SyntaxTree) .GetBinder(syntax.ReturnType, syntax, this); var constraints = this.MakeTypeParameterConstraintKinds( withTypeParametersBinder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses); ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, constraints); } return _lazyTypeParameterConstraintKinds; } public override bool IsVararg { get { LazyMethodChecks(); return _lazyIsVararg; } } protected override int GetParameterCountFromSyntax() => GetSyntax().ParameterList.ParameterCount; public override RefKind RefKind { get { return _refKind; } } internal static void InitializePartialMethodParts(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation) { Debug.Assert(definition.IsPartialDefinition); Debug.Assert(implementation.IsPartialImplementation); Debug.Assert((object)definition._otherPartOfPartial == null || (object)definition._otherPartOfPartial == implementation); Debug.Assert((object)implementation._otherPartOfPartial == null || (object)implementation._otherPartOfPartial == definition); definition._otherPartOfPartial = implementation; implementation._otherPartOfPartial = definition; } /// <summary> /// If this is a partial implementation part returns the definition part and vice versa. /// </summary> internal SourceOrdinaryMethodSymbol OtherPartOfPartial { get { return _otherPartOfPartial; } } /// <summary> /// Returns true if this symbol represents a partial method definition (the part that specifies a signature but no body). /// </summary> internal bool IsPartialDefinition { get { return this.IsPartial && !_hasAnyBody && !HasExternModifier; } } /// <summary> /// Returns true if this symbol represents a partial method implementation (the part that specifies both signature and body). /// </summary> internal bool IsPartialImplementation { get { return this.IsPartial && (_hasAnyBody || HasExternModifier); } } /// <summary> /// True if this is a partial method that doesn't have an implementation part. /// </summary> internal bool IsPartialWithoutImplementation { get { return this.IsPartialDefinition && (object)_otherPartOfPartial == null; } } /// <summary> /// Returns the implementation part of a partial method definition, /// or null if this is not a partial method or it is the definition part. /// </summary> internal SourceOrdinaryMethodSymbol SourcePartialDefinition { get { return this.IsPartialImplementation ? _otherPartOfPartial : null; } } /// <summary> /// Returns the definition part of a partial method implementation, /// or null if this is not a partial method or it is the implementation part. /// </summary> internal SourceOrdinaryMethodSymbol SourcePartialImplementation { get { return this.IsPartialDefinition ? _otherPartOfPartial : null; } } public override MethodSymbol PartialDefinitionPart { get { return SourcePartialDefinition; } } public override MethodSymbol PartialImplementationPart { get { return SourcePartialImplementation; } } public sealed override bool IsExtern { get { return IsPartialDefinition ? _otherPartOfPartial?.IsExtern ?? false : HasExternModifier; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { ref var lazyDocComment = ref expandIncludes ? ref this.lazyExpandedDocComment : ref this.lazyDocComment; return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(SourcePartialImplementation ?? this, expandIncludes, ref lazyDocComment); } protected override SourceMemberMethodSymbol BoundAttributesSource { get { return this.SourcePartialDefinition; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { if ((object)this.SourcePartialImplementation != null) { return OneOrMany.Create(ImmutableArray.Create(AttributeDeclarationSyntaxList, this.SourcePartialImplementation.AttributeDeclarationSyntaxList)); } else { return OneOrMany.Create(AttributeDeclarationSyntaxList); } } private SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList { get { var sourceContainer = this.ContainingType as SourceMemberContainerTypeSymbol; if ((object)sourceContainer != null && sourceContainer.AnyMemberHasAttributes) { return this.GetSyntax().AttributeLists; } return default(SyntaxList<AttributeListSyntax>); } } internal override bool IsExpressionBodied { get { return _isExpressionBodied; } } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); return ModifierUtils.MakeAndCheckNontypeMemberModifiers(syntax.Modifiers, defaultAccess: DeclarationModifiers.None, allowedModifiers, Locations[0], diagnostics, out _); } private ImmutableArray<TypeParameterSymbol> MakeTypeParameters(MethodDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax.TypeParameterList != null); OverriddenMethodTypeParameterMapBase typeMap = null; if (this.IsOverride) { typeMap = new OverriddenMethodTypeParameterMap(this); } else if (this.IsExplicitInterfaceImplementation) { typeMap = new ExplicitInterfaceMethodTypeParameterMap(this); } var typeParameters = syntax.TypeParameterList.Parameters; var result = ArrayBuilder<TypeParameterSymbol>.GetInstance(); for (int ordinal = 0; ordinal < typeParameters.Count; ordinal++) { var parameter = typeParameters[ordinal]; if (parameter.VarianceKeyword.Kind() != SyntaxKind.None) { diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, parameter.VarianceKeyword.GetLocation()); } var identifier = parameter.Identifier; var location = identifier.GetLocation(); var name = identifier.ValueText; // Note: It is not an error to have a type parameter named the same as its enclosing method: void M<M>() {} for (int i = 0; i < result.Count; i++) { if (name == result[i].Name) { diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, name); break; } } SourceMemberContainerTypeSymbol.ReportTypeNamedRecord(identifier.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, location); var tpEnclosing = ContainingType.FindEnclosingTypeParameter(name); if ((object)tpEnclosing != null) { // Type parameter '{0}' has the same name as the type parameter from outer type '{1}' diagnostics.Add(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, location, name, tpEnclosing.ContainingType); } var syntaxRefs = ImmutableArray.Create(parameter.GetReference()); var locations = ImmutableArray.Create(location); var typeParameter = (typeMap != null) ? (TypeParameterSymbol)new SourceOverridingMethodTypeParameterSymbol( typeMap, name, ordinal, locations, syntaxRefs) : new SourceMethodTypeParameterSymbol( this, name, ordinal, locations, syntaxRefs); result.Add(typeParameter); } return result.ToImmutableAndFree(); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { var implementingPart = this.SourcePartialImplementation; if ((object)implementingPart != null) { implementingPart.ForceComplete(locationOpt, cancellationToken); } base.ForceComplete(locationOpt, cancellationToken); } internal override bool IsDefinedInSourceTree( SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { // Since only the declaring (and not the implementing) part of a partial method appears in the member // list, we need to ensure we complete the implementation part when needed. return base.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) || this.SourcePartialImplementation?.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) == true; } protected override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { if ((object)_explicitInterfaceType != null) { var syntax = this.GetSyntax(); Debug.Assert(syntax.ExplicitInterfaceSpecifier != null); _explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, new SourceLocation(syntax.ExplicitInterfaceSpecifier.Name), diagnostics); } } protected override void PartialMethodChecks(BindingDiagnosticBag diagnostics) { var implementingPart = this.SourcePartialImplementation; if ((object)implementingPart != null) { PartialMethodChecks(this, implementingPart, diagnostics); } } /// <summary> /// Report differences between the defining and implementing /// parts of a partial method. Diagnostics are reported on the /// implementing part, matching Dev10 behavior. /// </summary> private static void PartialMethodChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(definition, implementation)); MethodSymbol constructedDefinition = definition.ConstructIfGeneric(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementation.TypeParameters)); bool hasTypeDifferences = !constructedDefinition.ReturnTypeWithAnnotations.Equals(implementation.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions); if (hasTypeDifferences) { diagnostics.Add(ErrorCode.ERR_PartialMethodReturnTypeDifference, implementation.Locations[0]); } else if (MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(definition, implementation)) { hasTypeDifferences = true; diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentTupleNames, implementation.Locations[0], definition, implementation); } if (definition.RefKind != implementation.RefKind) { diagnostics.Add(ErrorCode.ERR_PartialMethodRefReturnDifference, implementation.Locations[0]); } if (definition.IsStatic != implementation.IsStatic) { diagnostics.Add(ErrorCode.ERR_PartialMethodStaticDifference, implementation.Locations[0]); } if (definition.IsDeclaredReadOnly != implementation.IsDeclaredReadOnly) { diagnostics.Add(ErrorCode.ERR_PartialMethodReadOnlyDifference, implementation.Locations[0]); } if (definition.IsExtensionMethod != implementation.IsExtensionMethod) { diagnostics.Add(ErrorCode.ERR_PartialMethodExtensionDifference, implementation.Locations[0]); } if (definition.IsUnsafe != implementation.IsUnsafe && definition.CompilationAllowsUnsafe()) // Don't cascade. { diagnostics.Add(ErrorCode.ERR_PartialMethodUnsafeDifference, implementation.Locations[0]); } if (definition.IsParams() != implementation.IsParams()) { diagnostics.Add(ErrorCode.ERR_PartialMethodParamsDifference, implementation.Locations[0]); } if (definition.HasExplicitAccessModifier != implementation.HasExplicitAccessModifier || definition.DeclaredAccessibility != implementation.DeclaredAccessibility) { diagnostics.Add(ErrorCode.ERR_PartialMethodAccessibilityDifference, implementation.Locations[0]); } if (definition.IsVirtual != implementation.IsVirtual || definition.IsOverride != implementation.IsOverride || definition.IsSealed != implementation.IsSealed || definition.IsNew != implementation.IsNew) { diagnostics.Add(ErrorCode.ERR_PartialMethodExtendedModDifference, implementation.Locations[0]); } PartialMethodConstraintsChecks(definition, implementation, diagnostics); if (SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( implementation.DeclaringCompilation, constructedDefinition, implementation, diagnostics, static (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { // report only if this is an unsafe *nullability* difference diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial, implementingMethod.Locations[0]); }, static (diagnostics, implementedMethod, implementingMethod, implementingParameter, blameAttributes, arg) => { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat)); }, extraArgument: (object)null)) { hasTypeDifferences = true; } if ((!hasTypeDifferences && !MemberSignatureComparer.PartialMethodsStrictComparer.Equals(definition, implementation)) || hasDifferencesInParameterOrTypeParameterName(definition, implementation)) { diagnostics.Add(ErrorCode.WRN_PartialMethodTypeDifference, implementation.Locations[0], new FormattedSymbol(definition, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementation, SymbolDisplayFormat.MinimallyQualifiedFormat)); } static bool hasDifferencesInParameterOrTypeParameterName(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation) { return !definition.Parameters.SequenceEqual(implementation.Parameters, (a, b) => a.Name == b.Name) || !definition.TypeParameters.SequenceEqual(implementation.TypeParameters, (a, b) => a.Name == b.Name); } } private static void PartialMethodConstraintsChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(definition, implementation)); Debug.Assert(definition.Arity == implementation.Arity); var typeParameters1 = definition.TypeParameters; int arity = typeParameters1.Length; if (arity == 0) { return; } var typeParameters2 = implementation.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentConstraints, implementation.Locations[0], implementation, typeParameter2.Name); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, implementation.Locations[0], implementation, typeParameter2.Name); } } } internal override bool CallsAreOmitted(SyntaxTree syntaxTree) { if (this.IsPartialWithoutImplementation) { return true; } return base.CallsAreOmitted(syntaxTree); } internal override bool GenerateDebugInfo => !IsAsync && !IsIterator; } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbolBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Unlike <see cref="SourceOrdinaryMethodSymbol"/>, this type doesn't depend /// on any specific kind of syntax node associated with it. Any syntax node is good enough /// for it. /// </summary> internal abstract class SourceOrdinaryMethodSymbolBase : SourceOrdinaryMethodOrUserDefinedOperatorSymbol { private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly string _name; protected SourceOrdinaryMethodSymbolBase( NamedTypeSymbol containingType, string name, Location location, CSharpSyntaxNode syntax, MethodKind methodKind, bool isIterator, bool isExtensionMethod, bool isPartial, bool hasBody, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), location, isIterator: isIterator) { Debug.Assert(diagnostics.DiagnosticBag is object); _name = name; // The following two values are used to compute and store the initial value of the flags // However, these two components are placeholders; the correct value will be // computed lazily later and then the flags will be fixed up. const bool returnsVoid = false; DeclarationModifiers declarationModifiers; (declarationModifiers, HasExplicitAccessModifier) = this.MakeModifiers(methodKind, isPartial, hasBody, location, diagnostics); //explicit impls must be marked metadata virtual unless static var isMetadataVirtualIgnoringModifiers = methodKind == MethodKind.ExplicitInterfaceImplementation && (declarationModifiers & DeclarationModifiers.Static) == 0; this.MakeFlags(methodKind, declarationModifiers, returnsVoid, isExtensionMethod: isExtensionMethod, isNullableAnalysisEnabled: isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers: isMetadataVirtualIgnoringModifiers); _typeParameters = MakeTypeParameters(syntax, diagnostics); CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody, diagnostics); if (hasBody) { CheckModifiersForBody(location, diagnostics); } var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, isExplicitInterfaceImplementation: methodKind == MethodKind.ExplicitInterfaceImplementation); if (info != null) { diagnostics.Add(info, location); } } protected abstract ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics); #nullable enable protected override void MethodChecks(BindingDiagnosticBag diagnostics) { Debug.Assert(this.MethodKind != MethodKind.UserDefinedOperator, "SourceUserDefinedOperatorSymbolBase overrides this"); var (returnType, parameters, isVararg, declaredConstraints) = MakeParametersAndBindReturnType(diagnostics); MethodSymbol? overriddenOrExplicitlyImplementedMethod = MethodChecks(returnType, parameters, diagnostics); if (!declaredConstraints.IsDefault && overriddenOrExplicitlyImplementedMethod is object) { for (int i = 0; i < declaredConstraints.Length; i++) { var typeParameter = _typeParameters[i]; ErrorCode report; switch (declaredConstraints[i].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType | TypeParameterConstraintKind.Default)) { case TypeParameterConstraintKind.ReferenceType: if (!typeParameter.IsReferenceType) { report = ErrorCode.ERR_OverrideRefConstraintNotSatisfied; break; } continue; case TypeParameterConstraintKind.ValueType: if (!typeParameter.IsNonNullableValueType()) { report = ErrorCode.ERR_OverrideValConstraintNotSatisfied; break; } continue; case TypeParameterConstraintKind.Default: if (typeParameter.IsReferenceType || typeParameter.IsValueType) { report = ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied; break; } continue; default: continue; } diagnostics.Add(report, typeParameter.Locations[0], this, typeParameter, overriddenOrExplicitlyImplementedMethod.TypeParameters[i], overriddenOrExplicitlyImplementedMethod); } } CheckModifiers(MethodKind == MethodKind.ExplicitInterfaceImplementation, isVararg, HasAnyBody, locations[0], diagnostics); } #nullable disable protected abstract (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics); protected abstract bool HasAnyBody { get; } protected sealed override void LazyAsyncMethodChecks(CancellationToken cancellationToken) { Debug.Assert(this.IsPartial == state.HasComplete(CompletionPart.FinishMethodChecks), "Partial methods complete method checks during construction. " + "Other methods can't complete method checks before executing this method."); if (!this.IsAsync) { CompleteAsyncMethodChecks(diagnosticsOpt: null, cancellationToken: cancellationToken); return; } var diagnostics = BindingDiagnosticBag.GetInstance(); AsyncMethodChecks(diagnostics); CompleteAsyncMethodChecks(diagnostics, cancellationToken); diagnostics.Free(); } private void CompleteAsyncMethodChecks(BindingDiagnosticBag diagnosticsOpt, CancellationToken cancellationToken) { if (state.NotePartComplete(CompletionPart.StartAsyncMethodChecks)) { if (diagnosticsOpt != null) { AddDeclarationDiagnostics(diagnosticsOpt); } CompleteAsyncMethodChecksBetweenStartAndFinish(); state.NotePartComplete(CompletionPart.FinishAsyncMethodChecks); } else { state.SpinWaitComplete(CompletionPart.FinishAsyncMethodChecks, cancellationToken); } } protected abstract void CompleteAsyncMethodChecksBetweenStartAndFinish(); public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public override ImmutableArray<Location> Locations { get { return this.locations; } } public abstract override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)); public override string Name { get { return _name; } } protected abstract override SourceMemberMethodSymbol BoundAttributesSource { get; } internal abstract override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations(); internal bool HasExplicitAccessModifier { get; } private (DeclarationModifiers mods, bool hasExplicitAccessMod) MakeModifiers(MethodKind methodKind, bool isPartial, bool hasBody, Location location, BindingDiagnosticBag diagnostics) { bool isInterface = this.ContainingType.IsInterface; bool isExplicitInterfaceImplementation = methodKind == MethodKind.ExplicitInterfaceImplementation; var defaultAccess = isInterface && isPartial && !isExplicitInterfaceImplementation ? DeclarationModifiers.Public : DeclarationModifiers.Private; // Check that the set of modifiers is allowed var allowedModifiers = DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; var defaultInterfaceImplementationModifiers = DeclarationModifiers.None; if (!isExplicitInterfaceImplementation) { allowedModifiers |= DeclarationModifiers.New | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.AccessibilityMask; if (!isInterface) { allowedModifiers |= DeclarationModifiers.Override; } else { // This is needed to make sure we can detect 'public' modifier specified explicitly and // check it against language version below. defaultAccess = DeclarationModifiers.None; defaultInterfaceImplementationModifiers |= DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Extern | DeclarationModifiers.Async | DeclarationModifiers.Partial | DeclarationModifiers.AccessibilityMask; } } else { Debug.Assert(isExplicitInterfaceImplementation); if (isInterface) { allowedModifiers |= DeclarationModifiers.Abstract; } else { allowedModifiers |= DeclarationModifiers.Static; } } allowedModifiers |= DeclarationModifiers.Extern | DeclarationModifiers.Async; if (ContainingType.IsStructType()) { allowedModifiers |= DeclarationModifiers.ReadOnly; } // In order to detect whether explicit accessibility mods were provided, we pass the default value // for 'defaultAccess' and manually add in the 'defaultAccess' flags after the call. bool hasExplicitAccessMod; DeclarationModifiers mods = MakeDeclarationModifiers(allowedModifiers, diagnostics); if ((mods & DeclarationModifiers.AccessibilityMask) == 0) { hasExplicitAccessMod = false; mods |= defaultAccess; } else { hasExplicitAccessMod = true; } ModifierUtils.CheckFeatureAvailabilityForStaticAbstractMembersInInterfacesIfNeeded(mods, isExplicitInterfaceImplementation, location, diagnostics); this.CheckUnsafeModifier(mods, diagnostics); ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, mods, defaultInterfaceImplementationModifiers, location, diagnostics); mods = AddImpliedModifiers(mods, isInterface, methodKind, hasBody); return (mods, hasExplicitAccessMod); } protected abstract DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics); private static DeclarationModifiers AddImpliedModifiers(DeclarationModifiers mods, bool containingTypeIsInterface, MethodKind methodKind, bool hasBody) { // Let's overwrite modifiers for interface and explicit interface implementation methods with what they are supposed to be. // Proper errors must have been reported by now. if (containingTypeIsInterface) { mods = ModifierUtils.AdjustModifiersForAnInterfaceMember(mods, hasBody, methodKind == MethodKind.ExplicitInterfaceImplementation); } else if (methodKind == MethodKind.ExplicitInterfaceImplementation) { mods = (mods & ~DeclarationModifiers.AccessibilityMask) | DeclarationModifiers.Private; } return mods; } private const DeclarationModifiers PartialMethodExtendedModifierMask = DeclarationModifiers.Virtual | DeclarationModifiers.Override | DeclarationModifiers.New | DeclarationModifiers.Sealed | DeclarationModifiers.Extern; internal bool HasExtendedPartialModifier => (DeclarationModifiers & PartialMethodExtendedModifierMask) != 0; private void CheckModifiers(bool isExplicitInterfaceImplementation, bool isVararg, bool hasBody, Location location, BindingDiagnosticBag diagnostics) { Debug.Assert(!IsStatic || (!IsVirtual && !IsOverride)); // Otherwise 'virtual' and 'override' should have been reported and cleared earlier. bool isExplicitInterfaceImplementationInInterface = isExplicitInterfaceImplementation && ContainingType.IsInterface; if (IsPartial && HasExplicitAccessModifier) { Binder.CheckFeatureAvailability(SyntaxNode, MessageID.IDS_FeatureExtendedPartialMethods, diagnostics, location); } if (IsPartial && IsAbstract) { diagnostics.Add(ErrorCode.ERR_PartialMethodInvalidModifier, location); } else if (IsPartial && !HasExplicitAccessModifier && !ReturnsVoid) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, location, this); } else if (IsPartial && !HasExplicitAccessModifier && HasExtendedPartialModifier) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, location, this); } else if (IsPartial && !HasExplicitAccessModifier && Parameters.Any(p => p.RefKind == RefKind.Out)) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, location, this); } else if (this.DeclaredAccessibility == Accessibility.Private && (IsVirtual || (IsAbstract && !isExplicitInterfaceImplementationInInterface) || IsOverride)) { diagnostics.Add(ErrorCode.ERR_VirtualPrivate, location, this); } else if (IsStatic && IsAbstract && !ContainingType.IsInterface) { // A static member '{0}' cannot be marked as 'abstract' diagnostics.Add(ErrorCode.ERR_StaticNotVirtual, location, ModifierUtils.ConvertSingleModifierToSyntaxText(DeclarationModifiers.Abstract)); } else if (IsOverride && (IsNew || IsVirtual)) { // A member '{0}' marked as override cannot be marked as new or virtual diagnostics.Add(ErrorCode.ERR_OverrideNotNew, location, this); } else if (IsSealed && !IsOverride && !(isExplicitInterfaceImplementationInInterface && IsAbstract)) { // '{0}' cannot be sealed because it is not an override diagnostics.Add(ErrorCode.ERR_SealedNonOverride, location, this); } else if (IsSealed && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.SealedKeyword)); } else if (ReturnType.IsStatic) { // '{0}': static types cannot be used as return types diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(ContainingType.IsInterfaceType()), location, ReturnType); } else if (IsAbstract && IsExtern) { diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, location, this); } else if (IsAbstract && IsSealed && !isExplicitInterfaceImplementationInInterface) { diagnostics.Add(ErrorCode.ERR_AbstractAndSealed, location, this); } else if (IsAbstract && IsVirtual) { diagnostics.Add(ErrorCode.ERR_AbstractNotVirtual, location, this.Kind.Localize(), this); } else if (IsAbstract && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.AbstractKeyword)); } else if (IsVirtual && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.VirtualKeyword)); } else if (IsStatic && IsDeclaredReadOnly) { // Static member '{0}' cannot be marked 'readonly'. diagnostics.Add(ErrorCode.ERR_StaticMemberCantBeReadOnly, location, this); } else if (IsAbstract && !ContainingType.IsAbstract && (ContainingType.TypeKind == TypeKind.Class || ContainingType.TypeKind == TypeKind.Submission)) { // '{0}' is abstract but it is contained in non-abstract type '{1}' diagnostics.Add(ErrorCode.ERR_AbstractInConcreteClass, location, this, ContainingType); } else if (IsVirtual && ContainingType.IsSealed) { // '{0}' is a new virtual member in sealed type '{1}' diagnostics.Add(ErrorCode.ERR_NewVirtualInSealed, location, this, ContainingType); } else if (!hasBody && IsAsync) { diagnostics.Add(ErrorCode.ERR_BadAsyncLacksBody, location); } else if (!hasBody && !IsExtern && !IsAbstract && !IsPartial && !IsExpressionBodied) { diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); } else if (ContainingType.IsSealed && this.DeclaredAccessibility.HasProtected() && !this.IsOverride) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); } else if (ContainingType.IsStatic && !IsStatic) { diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, location, Name); } else if (isVararg && (IsGenericMethod || ContainingType.IsGenericType || Parameters.Length > 0 && Parameters[Parameters.Length - 1].IsParams)) { diagnostics.Add(ErrorCode.ERR_BadVarargs, location); } else if (isVararg && IsAsync) { diagnostics.Add(ErrorCode.ERR_VarargsAsync, location); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (this.IsExtensionMethod) { // No need to check if [Extension] attribute was explicitly set since // we'll issue CS1112 error in those cases and won't generate IL. var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Unlike <see cref="SourceOrdinaryMethodSymbol"/>, this type doesn't depend /// on any specific kind of syntax node associated with it. Any syntax node is good enough /// for it. /// </summary> internal abstract class SourceOrdinaryMethodSymbolBase : SourceOrdinaryMethodOrUserDefinedOperatorSymbol { private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly string _name; protected SourceOrdinaryMethodSymbolBase( NamedTypeSymbol containingType, string name, Location location, CSharpSyntaxNode syntax, MethodKind methodKind, bool isIterator, bool isExtensionMethod, bool isPartial, bool isReadOnly, bool hasBody, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), location, isIterator: isIterator) { Debug.Assert(diagnostics.DiagnosticBag is object); Debug.Assert(!isReadOnly || this.IsImplicitlyDeclared, "We only expect synthesized methods to use this flag to make a method readonly. Explicitly declared methods should get this value from modifiers in syntax."); _name = name; // The following two values are used to compute and store the initial value of the flags // However, these two components are placeholders; the correct value will be // computed lazily later and then the flags will be fixed up. const bool returnsVoid = false; DeclarationModifiers declarationModifiers; (declarationModifiers, HasExplicitAccessModifier) = this.MakeModifiers(methodKind, isPartial, isReadOnly, hasBody, location, diagnostics); //explicit impls must be marked metadata virtual unless static var isMetadataVirtualIgnoringModifiers = methodKind == MethodKind.ExplicitInterfaceImplementation && (declarationModifiers & DeclarationModifiers.Static) == 0; this.MakeFlags(methodKind, declarationModifiers, returnsVoid, isExtensionMethod: isExtensionMethod, isNullableAnalysisEnabled: isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers: isMetadataVirtualIgnoringModifiers); _typeParameters = MakeTypeParameters(syntax, diagnostics); CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody, diagnostics); if (hasBody) { CheckModifiersForBody(location, diagnostics); } var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, isExplicitInterfaceImplementation: methodKind == MethodKind.ExplicitInterfaceImplementation); if (info != null) { diagnostics.Add(info, location); } } protected abstract ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics); #nullable enable protected override void MethodChecks(BindingDiagnosticBag diagnostics) { Debug.Assert(this.MethodKind != MethodKind.UserDefinedOperator, "SourceUserDefinedOperatorSymbolBase overrides this"); var (returnType, parameters, isVararg, declaredConstraints) = MakeParametersAndBindReturnType(diagnostics); MethodSymbol? overriddenOrExplicitlyImplementedMethod = MethodChecks(returnType, parameters, diagnostics); if (!declaredConstraints.IsDefault && overriddenOrExplicitlyImplementedMethod is object) { for (int i = 0; i < declaredConstraints.Length; i++) { var typeParameter = _typeParameters[i]; ErrorCode report; switch (declaredConstraints[i].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.ValueType | TypeParameterConstraintKind.Default)) { case TypeParameterConstraintKind.ReferenceType: if (!typeParameter.IsReferenceType) { report = ErrorCode.ERR_OverrideRefConstraintNotSatisfied; break; } continue; case TypeParameterConstraintKind.ValueType: if (!typeParameter.IsNonNullableValueType()) { report = ErrorCode.ERR_OverrideValConstraintNotSatisfied; break; } continue; case TypeParameterConstraintKind.Default: if (typeParameter.IsReferenceType || typeParameter.IsValueType) { report = ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied; break; } continue; default: continue; } diagnostics.Add(report, typeParameter.Locations[0], this, typeParameter, overriddenOrExplicitlyImplementedMethod.TypeParameters[i], overriddenOrExplicitlyImplementedMethod); } } CheckModifiers(MethodKind == MethodKind.ExplicitInterfaceImplementation, isVararg, HasAnyBody, locations[0], diagnostics); } #nullable disable protected abstract (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics); protected abstract bool HasAnyBody { get; } protected sealed override void LazyAsyncMethodChecks(CancellationToken cancellationToken) { Debug.Assert(this.IsPartial == state.HasComplete(CompletionPart.FinishMethodChecks), "Partial methods complete method checks during construction. " + "Other methods can't complete method checks before executing this method."); if (!this.IsAsync) { CompleteAsyncMethodChecks(diagnosticsOpt: null, cancellationToken: cancellationToken); return; } var diagnostics = BindingDiagnosticBag.GetInstance(); AsyncMethodChecks(diagnostics); CompleteAsyncMethodChecks(diagnostics, cancellationToken); diagnostics.Free(); } private void CompleteAsyncMethodChecks(BindingDiagnosticBag diagnosticsOpt, CancellationToken cancellationToken) { if (state.NotePartComplete(CompletionPart.StartAsyncMethodChecks)) { if (diagnosticsOpt != null) { AddDeclarationDiagnostics(diagnosticsOpt); } CompleteAsyncMethodChecksBetweenStartAndFinish(); state.NotePartComplete(CompletionPart.FinishAsyncMethodChecks); } else { state.SpinWaitComplete(CompletionPart.FinishAsyncMethodChecks, cancellationToken); } } protected abstract void CompleteAsyncMethodChecksBetweenStartAndFinish(); public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public override ImmutableArray<Location> Locations { get { return this.locations; } } public abstract override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)); public override string Name { get { return _name; } } protected abstract override SourceMemberMethodSymbol BoundAttributesSource { get; } internal abstract override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations(); internal bool HasExplicitAccessModifier { get; } private (DeclarationModifiers mods, bool hasExplicitAccessMod) MakeModifiers(MethodKind methodKind, bool isPartial, bool isReadOnly, bool hasBody, Location location, BindingDiagnosticBag diagnostics) { bool isInterface = this.ContainingType.IsInterface; bool isExplicitInterfaceImplementation = methodKind == MethodKind.ExplicitInterfaceImplementation; var defaultAccess = isInterface && isPartial && !isExplicitInterfaceImplementation ? DeclarationModifiers.Public : DeclarationModifiers.Private; // Check that the set of modifiers is allowed var allowedModifiers = DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; var defaultInterfaceImplementationModifiers = DeclarationModifiers.None; if (!isExplicitInterfaceImplementation) { allowedModifiers |= DeclarationModifiers.New | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.AccessibilityMask; if (!isInterface) { allowedModifiers |= DeclarationModifiers.Override; } else { // This is needed to make sure we can detect 'public' modifier specified explicitly and // check it against language version below. defaultAccess = DeclarationModifiers.None; defaultInterfaceImplementationModifiers |= DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Extern | DeclarationModifiers.Async | DeclarationModifiers.Partial | DeclarationModifiers.AccessibilityMask; } } else { Debug.Assert(isExplicitInterfaceImplementation); if (isInterface) { allowedModifiers |= DeclarationModifiers.Abstract; } else { allowedModifiers |= DeclarationModifiers.Static; } } allowedModifiers |= DeclarationModifiers.Extern | DeclarationModifiers.Async; if (ContainingType.IsStructType()) { allowedModifiers |= DeclarationModifiers.ReadOnly; } // In order to detect whether explicit accessibility mods were provided, we pass the default value // for 'defaultAccess' and manually add in the 'defaultAccess' flags after the call. bool hasExplicitAccessMod; DeclarationModifiers mods = MakeDeclarationModifiers(allowedModifiers, diagnostics); if ((mods & DeclarationModifiers.AccessibilityMask) == 0) { hasExplicitAccessMod = false; mods |= defaultAccess; } else { hasExplicitAccessMod = true; } if (isReadOnly) { Debug.Assert(ContainingType.IsStructType()); mods |= DeclarationModifiers.ReadOnly; } ModifierUtils.CheckFeatureAvailabilityForStaticAbstractMembersInInterfacesIfNeeded(mods, isExplicitInterfaceImplementation, location, diagnostics); this.CheckUnsafeModifier(mods, diagnostics); ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, mods, defaultInterfaceImplementationModifiers, location, diagnostics); mods = AddImpliedModifiers(mods, isInterface, methodKind, hasBody); return (mods, hasExplicitAccessMod); } protected abstract DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics); private static DeclarationModifiers AddImpliedModifiers(DeclarationModifiers mods, bool containingTypeIsInterface, MethodKind methodKind, bool hasBody) { // Let's overwrite modifiers for interface and explicit interface implementation methods with what they are supposed to be. // Proper errors must have been reported by now. if (containingTypeIsInterface) { mods = ModifierUtils.AdjustModifiersForAnInterfaceMember(mods, hasBody, methodKind == MethodKind.ExplicitInterfaceImplementation); } else if (methodKind == MethodKind.ExplicitInterfaceImplementation) { mods = (mods & ~DeclarationModifiers.AccessibilityMask) | DeclarationModifiers.Private; } return mods; } private const DeclarationModifiers PartialMethodExtendedModifierMask = DeclarationModifiers.Virtual | DeclarationModifiers.Override | DeclarationModifiers.New | DeclarationModifiers.Sealed | DeclarationModifiers.Extern; internal bool HasExtendedPartialModifier => (DeclarationModifiers & PartialMethodExtendedModifierMask) != 0; private void CheckModifiers(bool isExplicitInterfaceImplementation, bool isVararg, bool hasBody, Location location, BindingDiagnosticBag diagnostics) { Debug.Assert(!IsStatic || (!IsVirtual && !IsOverride)); // Otherwise 'virtual' and 'override' should have been reported and cleared earlier. bool isExplicitInterfaceImplementationInInterface = isExplicitInterfaceImplementation && ContainingType.IsInterface; if (IsPartial && HasExplicitAccessModifier) { Binder.CheckFeatureAvailability(SyntaxNode, MessageID.IDS_FeatureExtendedPartialMethods, diagnostics, location); } if (IsPartial && IsAbstract) { diagnostics.Add(ErrorCode.ERR_PartialMethodInvalidModifier, location); } else if (IsPartial && !HasExplicitAccessModifier && !ReturnsVoid) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, location, this); } else if (IsPartial && !HasExplicitAccessModifier && HasExtendedPartialModifier) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, location, this); } else if (IsPartial && !HasExplicitAccessModifier && Parameters.Any(p => p.RefKind == RefKind.Out)) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, location, this); } else if (this.DeclaredAccessibility == Accessibility.Private && (IsVirtual || (IsAbstract && !isExplicitInterfaceImplementationInInterface) || IsOverride)) { diagnostics.Add(ErrorCode.ERR_VirtualPrivate, location, this); } else if (IsStatic && IsAbstract && !ContainingType.IsInterface) { // A static member '{0}' cannot be marked as 'abstract' diagnostics.Add(ErrorCode.ERR_StaticNotVirtual, location, ModifierUtils.ConvertSingleModifierToSyntaxText(DeclarationModifiers.Abstract)); } else if (IsOverride && (IsNew || IsVirtual)) { // A member '{0}' marked as override cannot be marked as new or virtual diagnostics.Add(ErrorCode.ERR_OverrideNotNew, location, this); } else if (IsSealed && !IsOverride && !(isExplicitInterfaceImplementationInInterface && IsAbstract)) { // '{0}' cannot be sealed because it is not an override diagnostics.Add(ErrorCode.ERR_SealedNonOverride, location, this); } else if (IsSealed && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.SealedKeyword)); } else if (ReturnType.IsStatic) { // '{0}': static types cannot be used as return types diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(ContainingType.IsInterfaceType()), location, ReturnType); } else if (IsAbstract && IsExtern) { diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, location, this); } else if (IsAbstract && IsSealed && !isExplicitInterfaceImplementationInInterface) { diagnostics.Add(ErrorCode.ERR_AbstractAndSealed, location, this); } else if (IsAbstract && IsVirtual) { diagnostics.Add(ErrorCode.ERR_AbstractNotVirtual, location, this.Kind.Localize(), this); } else if (IsAbstract && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.AbstractKeyword)); } else if (IsVirtual && ContainingType.TypeKind == TypeKind.Struct) { // The modifier '{0}' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.VirtualKeyword)); } else if (IsStatic && IsDeclaredReadOnly) { // Static member '{0}' cannot be marked 'readonly'. diagnostics.Add(ErrorCode.ERR_StaticMemberCantBeReadOnly, location, this); } else if (IsAbstract && !ContainingType.IsAbstract && (ContainingType.TypeKind == TypeKind.Class || ContainingType.TypeKind == TypeKind.Submission)) { // '{0}' is abstract but it is contained in non-abstract type '{1}' diagnostics.Add(ErrorCode.ERR_AbstractInConcreteClass, location, this, ContainingType); } else if (IsVirtual && ContainingType.IsSealed) { // '{0}' is a new virtual member in sealed type '{1}' diagnostics.Add(ErrorCode.ERR_NewVirtualInSealed, location, this, ContainingType); } else if (!hasBody && IsAsync) { diagnostics.Add(ErrorCode.ERR_BadAsyncLacksBody, location); } else if (!hasBody && !IsExtern && !IsAbstract && !IsPartial && !IsExpressionBodied) { diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); } else if (ContainingType.IsSealed && this.DeclaredAccessibility.HasProtected() && !this.IsOverride) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this); } else if (ContainingType.IsStatic && !IsStatic) { diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, location, Name); } else if (isVararg && (IsGenericMethod || ContainingType.IsGenericType || Parameters.Length > 0 && Parameters[Parameters.Length - 1].IsParams)) { diagnostics.Add(ErrorCode.ERR_BadVarargs, location); } else if (isVararg && IsAsync) { diagnostics.Add(ErrorCode.ERR_VarargsAsync, location); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (this.IsExtensionMethod) { // No need to check if [Extension] attribute was explicitly set since // we'll issue CS1112 error in those cases and won't generate IL. var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor)); } } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordBaseEquals.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// If the record type is derived from a base record type Base, the record type includes /// a synthesized override of the strongly-typed Equals(Base other). The synthesized /// override is sealed. It is an error if the override is declared explicitly. /// The synthesized override returns Equals((object?)other). /// </summary> internal sealed class SynthesizedRecordBaseEquals : SynthesizedRecordOrdinaryMethod { public SynthesizedRecordBaseEquals(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.ObjectEquals, hasBody: true, memberOffset, diagnostics) { } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { const DeclarationModifiers result = DeclarationModifiers.Public | DeclarationModifiers.Override | DeclarationModifiers.Sealed; Debug.Assert((result & ~allowedModifiers) == 0); return result; } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(ContainingType.BaseTypeNoUseSiteDiagnostics, NullableAnnotation.Annotated), ordinal: 0, RefKind.None, "other", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; protected override void MethodChecks(BindingDiagnosticBag diagnostics) { base.MethodChecks(diagnostics); var overridden = OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, Locations[0], this, ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.SyntaxNode, compilationState, diagnostics); try { ParameterSymbol parameter = Parameters[0]; if (parameter.Type.IsErrorType()) { F.CloseMethod(F.ThrowNull()); return; } var retExpr = F.Call( F.This(), ContainingType.GetMembersUnordered().OfType<SynthesizedRecordObjEquals>().Single(), F.Convert(F.SpecialType(SpecialType.System_Object), F.Parameter(parameter))); F.CloseMethod(F.Block(F.Return(retExpr))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// If the record type is derived from a base record type Base, the record type includes /// a synthesized override of the strongly-typed Equals(Base other). The synthesized /// override is sealed. It is an error if the override is declared explicitly. /// The synthesized override returns Equals((object?)other). /// </summary> internal sealed class SynthesizedRecordBaseEquals : SynthesizedRecordOrdinaryMethod { public SynthesizedRecordBaseEquals(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.ObjectEquals, isReadOnly: false, hasBody: true, memberOffset, diagnostics) { Debug.Assert(!containingType.IsRecordStruct); } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { const DeclarationModifiers result = DeclarationModifiers.Public | DeclarationModifiers.Override | DeclarationModifiers.Sealed; Debug.Assert((result & ~allowedModifiers) == 0); return result; } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(ContainingType.BaseTypeNoUseSiteDiagnostics, NullableAnnotation.Annotated), ordinal: 0, RefKind.None, "other", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; protected override void MethodChecks(BindingDiagnosticBag diagnostics) { base.MethodChecks(diagnostics); var overridden = OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, Locations[0], this, ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.SyntaxNode, compilationState, diagnostics); try { ParameterSymbol parameter = Parameters[0]; if (parameter.Type.IsErrorType()) { F.CloseMethod(F.ThrowNull()); return; } var retExpr = F.Call( F.This(), ContainingType.GetMembersUnordered().OfType<SynthesizedRecordObjEquals>().Single(), F.Convert(F.SpecialType(SpecialType.System_Object), F.Parameter(parameter))); F.CloseMethod(F.Block(F.Return(retExpr))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordClone.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// If a virtual "clone" method is present in the base record, the synthesized "clone" method overrides it /// and the return type of the method is the current containing type if the "covariant returns" feature is /// supported and the override return type otherwise. An error is produced if the base record clone method /// is sealed. If a virtual "clone" method is not present in the base record, the return type of the clone /// method is the containing type and the method is virtual, unless the record is sealed or abstract. /// If the containing record is abstract, the synthesized clone method is also abstract. /// If the "clone" method is not abstract, it returns the result of a call to a copy constructor. /// </summary> internal sealed class SynthesizedRecordClone : SynthesizedRecordOrdinaryMethod { public SynthesizedRecordClone( SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.CloneMethodName, hasBody: !containingType.IsAbstract, memberOffset, diagnostics) { } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { DeclarationModifiers result = DeclarationModifiers.Public; if (VirtualCloneInBase() is object) { result |= DeclarationModifiers.Override; } else { result |= ContainingType.IsSealed ? DeclarationModifiers.None : DeclarationModifiers.Virtual; } if (ContainingType.IsAbstract) { result &= ~DeclarationModifiers.Virtual; result |= DeclarationModifiers.Abstract; } Debug.Assert((result & ~allowedModifiers) == 0); #if DEBUG Debug.Assert(modifiersAreValid(result)); #endif return result; #if DEBUG static bool modifiersAreValid(DeclarationModifiers modifiers) { if ((modifiers & DeclarationModifiers.AccessibilityMask) != DeclarationModifiers.Public) { return false; } modifiers &= ~DeclarationModifiers.AccessibilityMask; switch (modifiers) { case DeclarationModifiers.None: return true; case DeclarationModifiers.Abstract: return true; case DeclarationModifiers.Override: return true; case DeclarationModifiers.Abstract | DeclarationModifiers.Override: return true; case DeclarationModifiers.Virtual: return true; default: return false; } } #endif } private MethodSymbol? VirtualCloneInBase() { NamedTypeSymbol baseType = ContainingType.BaseTypeNoUseSiteDiagnostics; if (!baseType.IsObjectType()) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; // This is reported when we bind bases return FindValidCloneMethod(baseType, ref discardedUseSiteInfo); } return null; } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { return (ReturnType: !ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses && VirtualCloneInBase() is { } baseClone ? baseClone.ReturnTypeWithAnnotations : TypeWithAnnotations.Create(isNullableEnabled: true, ContainingType), Parameters: ImmutableArray<ParameterSymbol>.Empty, IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 0; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { Debug.Assert(!IsAbstract); var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); try { if (ReturnType.IsErrorType()) { F.CloseMethod(F.ThrowNull()); return; } var members = ContainingType.InstanceConstructors; foreach (var member in members) { var ctor = (MethodSymbol)member; if (ctor.ParameterCount == 1 && ctor.Parameters[0].RefKind == RefKind.None && ctor.Parameters[0].Type.Equals(ContainingType, TypeCompareKind.AllIgnoreOptions)) { F.CloseMethod(F.Return(F.New(ctor, F.This()))); return; } } throw ExceptionUtilities.Unreachable; } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } internal static MethodSymbol? FindValidCloneMethod(TypeSymbol containingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (containingType.IsObjectType() || containingType is not NamedTypeSymbol containingNamedType) { return null; } // If this symbol is from metadata, getting all members can cause us to realize a lot of structures that we otherwise // don't have to. Optimize for the common case here of there not being a method named <Clone>$. If there is a method // with that name, it's most likely the one we're interested in, and we can't get around loading everything to find it. if (!containingNamedType.HasPossibleWellKnownCloneMethod()) { return null; } MethodSymbol? candidate = null; foreach (var member in containingType.GetMembers(WellKnownMemberNames.CloneMethodName)) { if (member is MethodSymbol { DeclaredAccessibility: Accessibility.Public, IsStatic: false, ParameterCount: 0, Arity: 0 } method) { if (candidate is object) { // An ambiguity case, can come from metadata, treat as an error for simplicity. return null; } candidate = method; } } if (candidate is null || !(containingType.IsSealed || candidate.IsOverride || candidate.IsVirtual || candidate.IsAbstract) || !containingType.IsEqualToOrDerivedFrom( candidate.ReturnType, TypeCompareKind.AllIgnoreOptions, ref useSiteInfo)) { return null; } return candidate; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// If a virtual "clone" method is present in the base record, the synthesized "clone" method overrides it /// and the return type of the method is the current containing type if the "covariant returns" feature is /// supported and the override return type otherwise. An error is produced if the base record clone method /// is sealed. If a virtual "clone" method is not present in the base record, the return type of the clone /// method is the containing type and the method is virtual, unless the record is sealed or abstract. /// If the containing record is abstract, the synthesized clone method is also abstract. /// If the "clone" method is not abstract, it returns the result of a call to a copy constructor. /// </summary> internal sealed class SynthesizedRecordClone : SynthesizedRecordOrdinaryMethod { public SynthesizedRecordClone( SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.CloneMethodName, isReadOnly: false, hasBody: !containingType.IsAbstract, memberOffset, diagnostics) { Debug.Assert(!containingType.IsRecordStruct); } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { DeclarationModifiers result = DeclarationModifiers.Public; if (VirtualCloneInBase() is object) { result |= DeclarationModifiers.Override; } else { result |= ContainingType.IsSealed ? DeclarationModifiers.None : DeclarationModifiers.Virtual; } if (ContainingType.IsAbstract) { result &= ~DeclarationModifiers.Virtual; result |= DeclarationModifiers.Abstract; } Debug.Assert((result & ~allowedModifiers) == 0); #if DEBUG Debug.Assert(modifiersAreValid(result)); #endif return result; #if DEBUG static bool modifiersAreValid(DeclarationModifiers modifiers) { if ((modifiers & DeclarationModifiers.AccessibilityMask) != DeclarationModifiers.Public) { return false; } modifiers &= ~DeclarationModifiers.AccessibilityMask; switch (modifiers) { case DeclarationModifiers.None: return true; case DeclarationModifiers.Abstract: return true; case DeclarationModifiers.Override: return true; case DeclarationModifiers.Abstract | DeclarationModifiers.Override: return true; case DeclarationModifiers.Virtual: return true; default: return false; } } #endif } private MethodSymbol? VirtualCloneInBase() { NamedTypeSymbol baseType = ContainingType.BaseTypeNoUseSiteDiagnostics; if (!baseType.IsObjectType()) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; // This is reported when we bind bases return FindValidCloneMethod(baseType, ref discardedUseSiteInfo); } return null; } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { return (ReturnType: !ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses && VirtualCloneInBase() is { } baseClone ? baseClone.ReturnTypeWithAnnotations : TypeWithAnnotations.Create(isNullableEnabled: true, ContainingType), Parameters: ImmutableArray<ParameterSymbol>.Empty, IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 0; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { Debug.Assert(!IsAbstract); var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); try { if (ReturnType.IsErrorType()) { F.CloseMethod(F.ThrowNull()); return; } var members = ContainingType.InstanceConstructors; foreach (var member in members) { var ctor = (MethodSymbol)member; if (ctor.ParameterCount == 1 && ctor.Parameters[0].RefKind == RefKind.None && ctor.Parameters[0].Type.Equals(ContainingType, TypeCompareKind.AllIgnoreOptions)) { F.CloseMethod(F.Return(F.New(ctor, F.This()))); return; } } throw ExceptionUtilities.Unreachable; } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } internal static MethodSymbol? FindValidCloneMethod(TypeSymbol containingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (containingType.IsObjectType() || containingType is not NamedTypeSymbol containingNamedType) { return null; } // If this symbol is from metadata, getting all members can cause us to realize a lot of structures that we otherwise // don't have to. Optimize for the common case here of there not being a method named <Clone>$. If there is a method // with that name, it's most likely the one we're interested in, and we can't get around loading everything to find it. if (!containingNamedType.HasPossibleWellKnownCloneMethod()) { return null; } MethodSymbol? candidate = null; foreach (var member in containingType.GetMembers(WellKnownMemberNames.CloneMethodName)) { if (member is MethodSymbol { DeclaredAccessibility: Accessibility.Public, IsStatic: false, ParameterCount: 0, Arity: 0 } method) { if (candidate is object) { // An ambiguity case, can come from metadata, treat as an error for simplicity. return null; } candidate = method; } } if (candidate is null || !(containingType.IsSealed || candidate.IsOverride || candidate.IsVirtual || candidate.IsAbstract) || !containingType.IsEqualToOrDerivedFrom( candidate.ReturnType, TypeCompareKind.AllIgnoreOptions, ref useSiteInfo)) { return null; } return candidate; } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordDeconstruct.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 { internal sealed class SynthesizedRecordDeconstruct : SynthesizedRecordOrdinaryMethod { private readonly SynthesizedRecordConstructor _ctor; private readonly ImmutableArray<Symbol> _positionalMembers; public SynthesizedRecordDeconstruct( SourceMemberContainerTypeSymbol containingType, SynthesizedRecordConstructor ctor, ImmutableArray<Symbol> positionalMembers, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.DeconstructMethodName, hasBody: true, memberOffset, diagnostics) { Debug.Assert(positionalMembers.All(p => p is PropertySymbol { GetMethod: not null } or FieldSymbol)); _ctor = ctor; _positionalMembers = positionalMembers; } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { const DeclarationModifiers result = DeclarationModifiers.Public; Debug.Assert((result & ~allowedModifiers) == 0); return result; } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Void, location, diagnostics)), Parameters: _ctor.Parameters.SelectAsArray<ParameterSymbol, ImmutableArray<Location>, ParameterSymbol>( (param, locations) => new SourceSimpleParameterSymbol(owner: this, param.TypeWithAnnotations, param.Ordinal, RefKind.Out, param.Name, locations), arg: Locations), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => _ctor.ParameterCount; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); if (ParameterCount != _positionalMembers.Length) { // There is a mismatch, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance(_positionalMembers.Length + 1); for (int i = 0; i < _positionalMembers.Length; i++) { var parameter = Parameters[i]; var positionalMember = _positionalMembers[i]; var type = positionalMember switch { PropertySymbol property => property.Type, FieldSymbol field => field.Type, _ => throw ExceptionUtilities.Unreachable }; if (!parameter.Type.Equals(type, TypeCompareKind.AllIgnoreOptions)) { // There is a mismatch, an error was reported elsewhere statementsBuilder.Free(); F.CloseMethod(F.ThrowNull()); return; } switch (positionalMember) { case PropertySymbol property: // parameter_i = property_i; statementsBuilder.Add(F.Assignment(F.Parameter(parameter), F.Property(F.This(), property))); break; case FieldSymbol field: // parameter_i = field_i; statementsBuilder.Add(F.Assignment(F.Parameter(parameter), F.Field(F.This(), field))); break; } } statementsBuilder.Add(F.Return()); F.CloseMethod(F.Block(statementsBuilder.ToImmutableAndFree())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 { internal sealed class SynthesizedRecordDeconstruct : SynthesizedRecordOrdinaryMethod { private readonly SynthesizedRecordConstructor _ctor; private readonly ImmutableArray<Symbol> _positionalMembers; public SynthesizedRecordDeconstruct( SourceMemberContainerTypeSymbol containingType, SynthesizedRecordConstructor ctor, ImmutableArray<Symbol> positionalMembers, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.DeconstructMethodName, isReadOnly: IsReadOnly(containingType, positionalMembers), hasBody: true, memberOffset, diagnostics) { Debug.Assert(positionalMembers.All(p => p is PropertySymbol { GetMethod: not null } or FieldSymbol)); _ctor = ctor; _positionalMembers = positionalMembers; } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { const DeclarationModifiers result = DeclarationModifiers.Public; Debug.Assert((result & ~allowedModifiers) == 0); return result; } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Void, location, diagnostics)), Parameters: _ctor.Parameters.SelectAsArray<ParameterSymbol, ImmutableArray<Location>, ParameterSymbol>( (param, locations) => new SourceSimpleParameterSymbol(owner: this, param.TypeWithAnnotations, param.Ordinal, RefKind.Out, param.Name, locations), arg: Locations), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => _ctor.ParameterCount; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); if (ParameterCount != _positionalMembers.Length) { // There is a mismatch, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance(_positionalMembers.Length + 1); for (int i = 0; i < _positionalMembers.Length; i++) { var parameter = Parameters[i]; var positionalMember = _positionalMembers[i]; var type = positionalMember switch { PropertySymbol property => property.Type, FieldSymbol field => field.Type, _ => throw ExceptionUtilities.Unreachable }; if (!parameter.Type.Equals(type, TypeCompareKind.AllIgnoreOptions)) { // There is a mismatch, an error was reported elsewhere statementsBuilder.Free(); F.CloseMethod(F.ThrowNull()); return; } switch (positionalMember) { case PropertySymbol property: // parameter_i = property_i; statementsBuilder.Add(F.Assignment(F.Parameter(parameter), F.Property(F.This(), property))); break; case FieldSymbol field: // parameter_i = field_i; statementsBuilder.Add(F.Assignment(F.Parameter(parameter), F.Field(F.This(), field))); break; } } statementsBuilder.Add(F.Return()); F.CloseMethod(F.Block(statementsBuilder.ToImmutableAndFree())); } private static bool IsReadOnly(SourceMemberContainerTypeSymbol containingType, ImmutableArray<Symbol> positionalMembers) { return containingType.IsReadOnly || (containingType.IsRecordStruct && !positionalMembers.Any(m => hasNonReadOnlyGetter(m))); static bool hasNonReadOnlyGetter(Symbol m) { if (m.Kind is SymbolKind.Property) { var property = (PropertySymbol)m; var getterMethod = property.GetMethod; return property.GetMethod is not null && !getterMethod.IsEffectivelyReadOnly; } return false; } } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedRecordEqualityContractProperty : SourcePropertySymbolBase { internal const string PropertyName = "EqualityContract"; public SynthesizedRecordEqualityContractProperty(SourceMemberContainerTypeSymbol containingType, BindingDiagnosticBag diagnostics) : base( containingType, syntax: (CSharpSyntaxNode)containingType.SyntaxReferences[0].GetSyntax(), hasGetAccessor: true, hasSetAccessor: false, isExplicitInterfaceImplementation: false, explicitInterfaceType: null, aliasQualifierOpt: null, modifiers: (containingType.IsSealed, containingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) switch { (true, true) => DeclarationModifiers.Private, (false, true) => DeclarationModifiers.Protected | DeclarationModifiers.Virtual, (_, false) => DeclarationModifiers.Protected | DeclarationModifiers.Override }, hasInitializer: false, isAutoProperty: false, isExpressionBodied: false, isInitOnly: false, RefKind.None, PropertyName, indexerNameAttributeLists: new SyntaxList<AttributeListSyntax>(), containingType.Locations[0], diagnostics) { } public override bool IsImplicitlyDeclared => true; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList => new SyntaxList<AttributeListSyntax>(); public override IAttributeTargetSymbol AttributesOwner => this; protected override Location TypeLocation => ContainingType.Locations[0]; protected override SourcePropertyAccessorSymbol CreateGetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) { return SourcePropertyAccessorSymbol.CreateAccessorSymbol( ContainingType, this, _modifiers, ContainingType.Locations[0], (CSharpSyntaxNode)((SourceMemberContainerTypeSymbol)ContainingType).SyntaxReferences[0].GetSyntax(), diagnostics); } protected override SourcePropertyAccessorSymbol CreateSetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) { throw ExceptionUtilities.Unreachable; } protected override (TypeWithAnnotations Type, ImmutableArray<ParameterSymbol> Parameters) MakeParametersAndBindType(BindingDiagnosticBag diagnostics) { return (TypeWithAnnotations.Create(Binder.GetWellKnownType(DeclaringCompilation, WellKnownType.System_Type, diagnostics, Location), NullableAnnotation.NotAnnotated), ImmutableArray<ParameterSymbol>.Empty); } protected override bool HasPointerTypeSyntactically => false; protected override void ValidatePropertyType(BindingDiagnosticBag diagnostics) { base.ValidatePropertyType(diagnostics); VerifyOverridesEqualityContractFromBase(this, diagnostics); } internal static void VerifyOverridesEqualityContractFromBase(PropertySymbol overriding, BindingDiagnosticBag diagnostics) { if (overriding.ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { return; } bool reportAnError = false; if (!overriding.IsOverride) { reportAnError = true; } else { var overridden = overriding.OverriddenProperty; if (overridden is object && !overridden.ContainingType.Equals(overriding.ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { reportAnError = true; } } if (reportAnError) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, overriding.Locations[0], overriding, overriding.ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal sealed class GetAccessorSymbol : SourcePropertyAccessorSymbol { internal GetAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbolBase property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) : base( containingType, property, propertyModifiers, location, syntax, hasBody: false, hasExpressionBody: false, isIterator: false, modifiers: new SyntaxTokenList(), MethodKind.PropertyGet, usesInit: false, isAutoPropertyAccessor: true, isNullableAnalysisEnabled: false, diagnostics) { } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; internal override bool SynthesizesLoweredBoundBody => true; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.GetNonNullSyntaxNode(), compilationState, diagnostics); try { F.CurrentFunction = this; F.CloseMethod(F.Block(F.Return(F.Typeof(ContainingType)))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedRecordEqualityContractProperty : SourcePropertySymbolBase { internal const string PropertyName = "EqualityContract"; public SynthesizedRecordEqualityContractProperty(SourceMemberContainerTypeSymbol containingType, BindingDiagnosticBag diagnostics) : base( containingType, syntax: (CSharpSyntaxNode)containingType.SyntaxReferences[0].GetSyntax(), hasGetAccessor: true, hasSetAccessor: false, isExplicitInterfaceImplementation: false, explicitInterfaceType: null, aliasQualifierOpt: null, modifiers: (containingType.IsSealed, containingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) switch { (true, true) => DeclarationModifiers.Private, (false, true) => DeclarationModifiers.Protected | DeclarationModifiers.Virtual, (_, false) => DeclarationModifiers.Protected | DeclarationModifiers.Override }, hasInitializer: false, isAutoProperty: false, isExpressionBodied: false, isInitOnly: false, RefKind.None, PropertyName, indexerNameAttributeLists: new SyntaxList<AttributeListSyntax>(), containingType.Locations[0], diagnostics) { Debug.Assert(!containingType.IsRecordStruct); } public override bool IsImplicitlyDeclared => true; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList => new SyntaxList<AttributeListSyntax>(); public override IAttributeTargetSymbol AttributesOwner => this; protected override Location TypeLocation => ContainingType.Locations[0]; protected override SourcePropertyAccessorSymbol CreateGetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) { return SourcePropertyAccessorSymbol.CreateAccessorSymbol( ContainingType, this, _modifiers, ContainingType.Locations[0], (CSharpSyntaxNode)((SourceMemberContainerTypeSymbol)ContainingType).SyntaxReferences[0].GetSyntax(), diagnostics); } protected override SourcePropertyAccessorSymbol CreateSetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) { throw ExceptionUtilities.Unreachable; } protected override (TypeWithAnnotations Type, ImmutableArray<ParameterSymbol> Parameters) MakeParametersAndBindType(BindingDiagnosticBag diagnostics) { return (TypeWithAnnotations.Create(Binder.GetWellKnownType(DeclaringCompilation, WellKnownType.System_Type, diagnostics, Location), NullableAnnotation.NotAnnotated), ImmutableArray<ParameterSymbol>.Empty); } protected override bool HasPointerTypeSyntactically => false; protected override void ValidatePropertyType(BindingDiagnosticBag diagnostics) { base.ValidatePropertyType(diagnostics); VerifyOverridesEqualityContractFromBase(this, diagnostics); } internal static void VerifyOverridesEqualityContractFromBase(PropertySymbol overriding, BindingDiagnosticBag diagnostics) { if (overriding.ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { return; } bool reportAnError = false; if (!overriding.IsOverride) { reportAnError = true; } else { var overridden = overriding.OverriddenProperty; if (overridden is object && !overridden.ContainingType.Equals(overriding.ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { reportAnError = true; } } if (reportAnError) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, overriding.Locations[0], overriding, overriding.ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal sealed class GetAccessorSymbol : SourcePropertyAccessorSymbol { internal GetAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbolBase property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) : base( containingType, property, propertyModifiers, location, syntax, hasBody: false, hasExpressionBody: false, isIterator: false, modifiers: new SyntaxTokenList(), MethodKind.PropertyGet, usesInit: false, isAutoPropertyAccessor: true, isNullableAnalysisEnabled: false, diagnostics) { } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; internal override bool SynthesizesLoweredBoundBody => true; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.GetNonNullSyntaxNode(), compilationState, diagnostics); try { F.CurrentFunction = this; F.CloseMethod(F.Block(F.Return(F.Typeof(ContainingType)))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEquals.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Unless explicitly declared, a record includes a synthesized strongly-typed overload /// of `Equals(R? other)` where `R` is the record type. /// The method is `public`, and the method is `virtual` unless the record type is `sealed`. /// </summary> internal sealed class SynthesizedRecordEquals : SynthesizedRecordOrdinaryMethod { private readonly PropertySymbol? _equalityContract; public SynthesizedRecordEquals(SourceMemberContainerTypeSymbol containingType, PropertySymbol? equalityContract, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.ObjectEquals, hasBody: true, memberOffset, diagnostics) { Debug.Assert(equalityContract is null == containingType.IsRecordStruct); _equalityContract = equalityContract; } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { DeclarationModifiers result = DeclarationModifiers.Public | (ContainingType.IsSealed ? DeclarationModifiers.None : DeclarationModifiers.Virtual); Debug.Assert((result & ~allowedModifiers) == 0); return result; } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; var annotation = ContainingType.IsRecordStruct ? NullableAnnotation.Oblivious : NullableAnnotation.Annotated; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(ContainingType, annotation), ordinal: 0, RefKind.None, "other", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); try { var other = F.Parameter(Parameters[0]); BoundExpression? retExpr; // This method is the strongly-typed Equals method where the parameter type is // the containing type. bool isRecordStruct = ContainingType.IsRecordStruct; if (isRecordStruct) { // We'll produce: // bool Equals(T other) => // field1 == other.field1 && ... && fieldN == other.fieldN; // or simply true if no fields. retExpr = null; } else if (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { Debug.Assert(_equalityContract is not null); if (_equalityContract.GetMethod is null) { // The equality contract isn't usable, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } if (_equalityContract.IsStatic || !_equalityContract.Type.Equals(DeclaringCompilation.GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.AllIgnoreOptions)) { // There is a signature mismatch, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } // There are no base record types. // The definition of the method is as follows // // virtual bool Equals(T other) => // other != null && // EqualityContract == other.EqualityContract && // field1 == other.field1 && ... && fieldN == other.fieldN; // other != null Debug.Assert(!other.Type.IsStructType()); retExpr = F.ObjectNotEqual(other, F.Null(F.SpecialType(SpecialType.System_Object))); // EqualityContract == other.EqualityContract var contractsEqual = F.Call(receiver: null, F.WellKnownMethod(WellKnownMember.System_Type__op_Equality), F.Property(F.This(), _equalityContract), F.Property(other, _equalityContract)); retExpr = F.LogicalAnd(retExpr, contractsEqual); } else { MethodSymbol? baseEquals = ContainingType.GetMembersUnordered().OfType<SynthesizedRecordBaseEquals>().Single().OverriddenMethod; if (baseEquals is null || !baseEquals.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions) || baseEquals.ReturnType.SpecialType != SpecialType.System_Boolean) { // There was a problem with overriding of base equals, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } // There are base record types. // The definition of the method is as follows, and baseEquals // is the corresponding method on the nearest base record type to // delegate to: // // virtual bool Equals(Derived other) => // (object)other == this || (base.Equals((Base)other) && // field1 == other.field1 && ... && fieldN == other.fieldN); retExpr = F.Call( F.Base(baseEquals.ContainingType), baseEquals, F.Convert(baseEquals.Parameters[0].Type, other)); } // field1 == other.field1 && ... && fieldN == other.fieldN var fields = ArrayBuilder<FieldSymbol>.GetInstance(); bool foundBadField = false; foreach (var f in ContainingType.GetFieldsToEmit()) { if (!f.IsStatic) { fields.Add(f); var parameterType = f.Type; if (parameterType.IsUnsafe()) { diagnostics.Add(ErrorCode.ERR_BadFieldTypeInRecord, f.Locations.FirstOrNone(), parameterType); foundBadField = true; } else if (parameterType.IsRestrictedType()) { // We'll have reported a diagnostic elsewhere (SourceMemberFieldSymbol.TypeChecks) foundBadField = true; } } } if (fields.Count > 0 && !foundBadField) { retExpr = MethodBodySynthesizer.GenerateFieldEquals( retExpr, other, fields, F); } else if (retExpr is null) { retExpr = F.Literal(true); } fields.Free(); if (!isRecordStruct) { retExpr = F.LogicalOr(F.ObjectEqual(F.This(), other), retExpr); } F.CloseMethod(F.Block(F.Return(retExpr))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Unless explicitly declared, a record includes a synthesized strongly-typed overload /// of `Equals(R? other)` where `R` is the record type. /// The method is `public`, and the method is `virtual` unless the record type is `sealed`. /// </summary> internal sealed class SynthesizedRecordEquals : SynthesizedRecordOrdinaryMethod { private readonly PropertySymbol? _equalityContract; public SynthesizedRecordEquals(SourceMemberContainerTypeSymbol containingType, PropertySymbol? equalityContract, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.ObjectEquals, isReadOnly: containingType.IsRecordStruct, hasBody: true, memberOffset, diagnostics) { Debug.Assert(equalityContract is null == containingType.IsRecordStruct); _equalityContract = equalityContract; } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { DeclarationModifiers result = DeclarationModifiers.Public | (ContainingType.IsSealed ? DeclarationModifiers.None : DeclarationModifiers.Virtual); Debug.Assert((result & ~allowedModifiers) == 0); return result; } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; var annotation = ContainingType.IsRecordStruct ? NullableAnnotation.Oblivious : NullableAnnotation.Annotated; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(ContainingType, annotation), ordinal: 0, RefKind.None, "other", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); try { var other = F.Parameter(Parameters[0]); BoundExpression? retExpr; // This method is the strongly-typed Equals method where the parameter type is // the containing type. bool isRecordStruct = ContainingType.IsRecordStruct; if (isRecordStruct) { // We'll produce: // bool Equals(T other) => // field1 == other.field1 && ... && fieldN == other.fieldN; // or simply true if no fields. retExpr = null; } else if (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { Debug.Assert(_equalityContract is not null); if (_equalityContract.GetMethod is null) { // The equality contract isn't usable, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } if (_equalityContract.IsStatic || !_equalityContract.Type.Equals(DeclaringCompilation.GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.AllIgnoreOptions)) { // There is a signature mismatch, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } // There are no base record types. // The definition of the method is as follows // // virtual bool Equals(T other) => // other != null && // EqualityContract == other.EqualityContract && // field1 == other.field1 && ... && fieldN == other.fieldN; // other != null Debug.Assert(!other.Type.IsStructType()); retExpr = F.ObjectNotEqual(other, F.Null(F.SpecialType(SpecialType.System_Object))); // EqualityContract == other.EqualityContract var contractsEqual = F.Call(receiver: null, F.WellKnownMethod(WellKnownMember.System_Type__op_Equality), F.Property(F.This(), _equalityContract), F.Property(other, _equalityContract)); retExpr = F.LogicalAnd(retExpr, contractsEqual); } else { MethodSymbol? baseEquals = ContainingType.GetMembersUnordered().OfType<SynthesizedRecordBaseEquals>().Single().OverriddenMethod; if (baseEquals is null || !baseEquals.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions) || baseEquals.ReturnType.SpecialType != SpecialType.System_Boolean) { // There was a problem with overriding of base equals, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } // There are base record types. // The definition of the method is as follows, and baseEquals // is the corresponding method on the nearest base record type to // delegate to: // // virtual bool Equals(Derived other) => // (object)other == this || (base.Equals((Base)other) && // field1 == other.field1 && ... && fieldN == other.fieldN); retExpr = F.Call( F.Base(baseEquals.ContainingType), baseEquals, F.Convert(baseEquals.Parameters[0].Type, other)); } // field1 == other.field1 && ... && fieldN == other.fieldN var fields = ArrayBuilder<FieldSymbol>.GetInstance(); bool foundBadField = false; foreach (var f in ContainingType.GetFieldsToEmit()) { if (!f.IsStatic) { fields.Add(f); var parameterType = f.Type; if (parameterType.IsUnsafe()) { diagnostics.Add(ErrorCode.ERR_BadFieldTypeInRecord, f.Locations.FirstOrNone(), parameterType); foundBadField = true; } else if (parameterType.IsRestrictedType()) { // We'll have reported a diagnostic elsewhere (SourceMemberFieldSymbol.TypeChecks) foundBadField = true; } } } if (fields.Count > 0 && !foundBadField) { retExpr = MethodBodySynthesizer.GenerateFieldEquals( retExpr, other, fields, F); } else if (retExpr is null) { retExpr = F.Literal(true); } fields.Free(); if (!isRecordStruct) { retExpr = F.LogicalOr(F.ObjectEqual(F.This(), other), retExpr); } F.CloseMethod(F.Block(F.Return(retExpr))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordGetHashCode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The record type includes a synthesized override of object.GetHashCode(). /// The method can be declared explicitly. It is an error if the explicit /// declaration is sealed unless the record type is sealed. /// </summary> internal sealed class SynthesizedRecordGetHashCode : SynthesizedRecordObjectMethod { private readonly PropertySymbol? _equalityContract; public SynthesizedRecordGetHashCode(SourceMemberContainerTypeSymbol containingType, PropertySymbol? equalityContract, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.ObjectGetHashCode, memberOffset, diagnostics) { Debug.Assert(containingType.IsRecordStruct == equalityContract is null); _equalityContract = equalityContract; } protected override SpecialMember OverriddenSpecialMember => SpecialMember.System_Object__GetHashCode; protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Int32, location, diagnostics)), Parameters: ImmutableArray<ParameterSymbol>.Empty, IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 0; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.SyntaxNode, compilationState, diagnostics); try { MethodSymbol? equalityComparer_GetHashCode = null; MethodSymbol? equalityComparer_get_Default = null; BoundExpression? currentHashValue; if (ContainingType.IsRecordStruct) { currentHashValue = null; } else if (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { Debug.Assert(_equalityContract is not null); if (_equalityContract.GetMethod is null) { // The equality contract isn't usable, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } if (_equalityContract.IsStatic) { F.CloseMethod(F.ThrowNull()); return; } // There are no base record types. // Get hash code of the equality contract and combine it with hash codes for field values. ensureEqualityComparerHelpers(F, ref equalityComparer_GetHashCode, ref equalityComparer_get_Default); currentHashValue = MethodBodySynthesizer.GenerateGetHashCode(equalityComparer_GetHashCode, equalityComparer_get_Default, F.Property(F.This(), _equalityContract), F); } else { // There are base record types. // Get base.GetHashCode() and combine it with hash codes for field values. var overridden = OverriddenMethod; if (overridden is null || overridden.ReturnType.SpecialType != SpecialType.System_Int32) { // There was a problem with overriding, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } currentHashValue = F.Call(F.Base(overridden.ContainingType), overridden); } // bound HASH_FACTOR BoundLiteral? boundHashFactor = null; foreach (var f in ContainingType.GetFieldsToEmit()) { if (!f.IsStatic) { ensureEqualityComparerHelpers(F, ref equalityComparer_GetHashCode, ref equalityComparer_get_Default); if (currentHashValue is null) { // EqualityComparer<field type>.Default.GetHashCode(this.field) currentHashValue = MethodBodySynthesizer.GenerateGetHashCode(equalityComparer_GetHashCode, equalityComparer_get_Default, F.Field(F.This(), f), F); } else { currentHashValue = MethodBodySynthesizer.GenerateHashCombine(currentHashValue, equalityComparer_GetHashCode, equalityComparer_get_Default, ref boundHashFactor, F.Field(F.This(), f), F); } } } if (currentHashValue is null) { currentHashValue = F.Literal(0); } F.CloseMethod(F.Block(F.Return(currentHashValue))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } static void ensureEqualityComparerHelpers(SyntheticBoundNodeFactory F, [NotNull] ref MethodSymbol? equalityComparer_GetHashCode, [NotNull] ref MethodSymbol? equalityComparer_get_Default) { equalityComparer_GetHashCode ??= F.WellKnownMethod(WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode); equalityComparer_get_Default ??= F.WellKnownMethod(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The record type includes a synthesized override of object.GetHashCode(). /// The method can be declared explicitly. It is an error if the explicit /// declaration is sealed unless the record type is sealed. /// </summary> internal sealed class SynthesizedRecordGetHashCode : SynthesizedRecordObjectMethod { private readonly PropertySymbol? _equalityContract; public SynthesizedRecordGetHashCode(SourceMemberContainerTypeSymbol containingType, PropertySymbol? equalityContract, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.ObjectGetHashCode, memberOffset, isReadOnly: containingType.IsRecordStruct, diagnostics) { Debug.Assert(containingType.IsRecordStruct == equalityContract is null); _equalityContract = equalityContract; } protected override SpecialMember OverriddenSpecialMember => SpecialMember.System_Object__GetHashCode; protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Int32, location, diagnostics)), Parameters: ImmutableArray<ParameterSymbol>.Empty, IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 0; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.SyntaxNode, compilationState, diagnostics); try { MethodSymbol? equalityComparer_GetHashCode = null; MethodSymbol? equalityComparer_get_Default = null; BoundExpression? currentHashValue; if (ContainingType.IsRecordStruct) { currentHashValue = null; } else if (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { Debug.Assert(_equalityContract is not null); if (_equalityContract.GetMethod is null) { // The equality contract isn't usable, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } if (_equalityContract.IsStatic) { F.CloseMethod(F.ThrowNull()); return; } // There are no base record types. // Get hash code of the equality contract and combine it with hash codes for field values. ensureEqualityComparerHelpers(F, ref equalityComparer_GetHashCode, ref equalityComparer_get_Default); currentHashValue = MethodBodySynthesizer.GenerateGetHashCode(equalityComparer_GetHashCode, equalityComparer_get_Default, F.Property(F.This(), _equalityContract), F); } else { // There are base record types. // Get base.GetHashCode() and combine it with hash codes for field values. var overridden = OverriddenMethod; if (overridden is null || overridden.ReturnType.SpecialType != SpecialType.System_Int32) { // There was a problem with overriding, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } currentHashValue = F.Call(F.Base(overridden.ContainingType), overridden); } // bound HASH_FACTOR BoundLiteral? boundHashFactor = null; foreach (var f in ContainingType.GetFieldsToEmit()) { if (!f.IsStatic) { ensureEqualityComparerHelpers(F, ref equalityComparer_GetHashCode, ref equalityComparer_get_Default); if (currentHashValue is null) { // EqualityComparer<field type>.Default.GetHashCode(this.field) currentHashValue = MethodBodySynthesizer.GenerateGetHashCode(equalityComparer_GetHashCode, equalityComparer_get_Default, F.Field(F.This(), f), F); } else { currentHashValue = MethodBodySynthesizer.GenerateHashCombine(currentHashValue, equalityComparer_GetHashCode, equalityComparer_get_Default, ref boundHashFactor, F.Field(F.This(), f), F); } } } if (currentHashValue is null) { currentHashValue = F.Literal(0); } F.CloseMethod(F.Block(F.Return(currentHashValue))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } static void ensureEqualityComparerHelpers(SyntheticBoundNodeFactory F, [NotNull] ref MethodSymbol? equalityComparer_GetHashCode, [NotNull] ref MethodSymbol? equalityComparer_get_Default) { equalityComparer_GetHashCode ??= F.WellKnownMethod(WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode); equalityComparer_get_Default ??= F.WellKnownMethod(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); } } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordObjEquals.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Symbols { /// <summary> /// The record type includes a synthesized override of object.Equals(object? obj). /// It is an error if the override is declared explicitly. The synthesized override /// returns Equals(other as R) where R is the record type. /// </summary> internal sealed class SynthesizedRecordObjEquals : SynthesizedRecordObjectMethod { private readonly MethodSymbol _typedRecordEquals; public SynthesizedRecordObjEquals(SourceMemberContainerTypeSymbol containingType, MethodSymbol typedRecordEquals, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.ObjectEquals, memberOffset, diagnostics) { _typedRecordEquals = typedRecordEquals; } protected override SpecialMember OverriddenSpecialMember => SpecialMember.System_Object__Equals; 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.Annotated; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Object, location, diagnostics), annotation), ordinal: 0, RefKind.None, "obj", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.SyntaxNode, compilationState, diagnostics); try { if (_typedRecordEquals.ReturnType.SpecialType != SpecialType.System_Boolean) { // There is a signature mismatch, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } var paramAccess = F.Parameter(Parameters[0]); BoundExpression expression; if (ContainingType.IsRecordStruct) { // For record structs: // return other is R && Equals((R)other) expression = F.LogicalAnd( F.Is(paramAccess, ContainingType), F.Call(F.This(), _typedRecordEquals, F.Convert(ContainingType, paramAccess))); } else { // For record classes: // return this.Equals(param as ContainingType); expression = F.Call(F.This(), _typedRecordEquals, F.As(paramAccess, ContainingType)); } F.CloseMethod(F.Block(ImmutableArray.Create<BoundStatement>(F.Return(expression)))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The record type includes a synthesized override of object.Equals(object? obj). /// It is an error if the override is declared explicitly. The synthesized override /// returns Equals(other as R) where R is the record type. /// </summary> internal sealed class SynthesizedRecordObjEquals : SynthesizedRecordObjectMethod { private readonly MethodSymbol _typedRecordEquals; public SynthesizedRecordObjEquals(SourceMemberContainerTypeSymbol containingType, MethodSymbol typedRecordEquals, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.ObjectEquals, memberOffset, isReadOnly: containingType.IsRecordStruct, diagnostics) { _typedRecordEquals = typedRecordEquals; } protected override SpecialMember OverriddenSpecialMember => SpecialMember.System_Object__Equals; 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.Annotated; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Object, location, diagnostics), annotation), ordinal: 0, RefKind.None, "obj", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.SyntaxNode, compilationState, diagnostics); try { if (_typedRecordEquals.ReturnType.SpecialType != SpecialType.System_Boolean) { // There is a signature mismatch, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } var paramAccess = F.Parameter(Parameters[0]); BoundExpression expression; if (ContainingType.IsRecordStruct) { // For record structs: // return other is R && Equals((R)other) expression = F.LogicalAnd( F.Is(paramAccess, ContainingType), F.Call(F.This(), _typedRecordEquals, F.Convert(ContainingType, paramAccess))); } else { // For record classes: // return this.Equals(param as ContainingType); expression = F.Call(F.This(), _typedRecordEquals, F.As(paramAccess, ContainingType)); } F.CloseMethod(F.Block(ImmutableArray.Create<BoundStatement>(F.Return(expression)))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordObjectMethod.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Common base for ordinary methods overriding methods from object synthesized by compiler for records. /// </summary> internal abstract class SynthesizedRecordObjectMethod : SynthesizedRecordOrdinaryMethod { protected SynthesizedRecordObjectMethod(SourceMemberContainerTypeSymbol containingType, string name, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, name, hasBody: true, memberOffset, diagnostics) { } protected sealed override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { const DeclarationModifiers result = DeclarationModifiers.Public | DeclarationModifiers.Override; Debug.Assert((result & ~allowedModifiers) == 0); return result; } protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics) { base.MethodChecks(diagnostics); VerifyOverridesMethodFromObject(this, OverriddenSpecialMember, diagnostics); } protected abstract SpecialMember OverriddenSpecialMember { get; } /// <summary> /// Returns true if reported an error /// </summary> internal static bool VerifyOverridesMethodFromObject(MethodSymbol overriding, SpecialMember overriddenSpecialMember, BindingDiagnosticBag diagnostics) { bool reportAnError = false; if (!overriding.IsOverride) { reportAnError = true; } else { var overridden = overriding.OverriddenMethod?.OriginalDefinition; if (overridden is object && !(overridden.ContainingType is SourceMemberContainerTypeSymbol { IsRecord: true } && overridden.ContainingModule == overriding.ContainingModule)) { MethodSymbol leastOverridden = overriding.GetLeastOverriddenMethod(accessingTypeOpt: null); reportAnError = (object)leastOverridden != overriding.ContainingAssembly.GetSpecialTypeMember(overriddenSpecialMember) && leastOverridden.ReturnType.Equals(overriding.ReturnType, TypeCompareKind.AllIgnoreOptions); } } if (reportAnError) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideMethodFromObject, overriding.Locations[0], overriding); } return reportAnError; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Common base for ordinary methods overriding methods from object synthesized by compiler for records. /// </summary> internal abstract class SynthesizedRecordObjectMethod : SynthesizedRecordOrdinaryMethod { protected SynthesizedRecordObjectMethod(SourceMemberContainerTypeSymbol containingType, string name, int memberOffset, bool isReadOnly, BindingDiagnosticBag diagnostics) : base(containingType, name, isReadOnly: isReadOnly, hasBody: true, memberOffset, diagnostics) { } protected sealed override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { const DeclarationModifiers result = DeclarationModifiers.Public | DeclarationModifiers.Override; Debug.Assert((result & ~allowedModifiers) == 0); return result; } protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics) { base.MethodChecks(diagnostics); VerifyOverridesMethodFromObject(this, OverriddenSpecialMember, diagnostics); } protected abstract SpecialMember OverriddenSpecialMember { get; } /// <summary> /// Returns true if reported an error /// </summary> internal static bool VerifyOverridesMethodFromObject(MethodSymbol overriding, SpecialMember overriddenSpecialMember, BindingDiagnosticBag diagnostics) { bool reportAnError = false; if (!overriding.IsOverride) { reportAnError = true; } else { var overridden = overriding.OverriddenMethod?.OriginalDefinition; if (overridden is object && !(overridden.ContainingType is SourceMemberContainerTypeSymbol { IsRecord: true } && overridden.ContainingModule == overriding.ContainingModule)) { MethodSymbol leastOverridden = overriding.GetLeastOverriddenMethod(accessingTypeOpt: null); reportAnError = (object)leastOverridden != overriding.ContainingAssembly.GetSpecialTypeMember(overriddenSpecialMember) && leastOverridden.ReturnType.Equals(overriding.ReturnType, TypeCompareKind.AllIgnoreOptions); } } if (reportAnError) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideMethodFromObject, overriding.Locations[0], overriding); } return reportAnError; } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordOrdinaryMethod.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Common base for ordinary methods synthesized by compiler for records. /// </summary> internal abstract class SynthesizedRecordOrdinaryMethod : SourceOrdinaryMethodSymbolBase { private readonly int _memberOffset; protected SynthesizedRecordOrdinaryMethod(SourceMemberContainerTypeSymbol containingType, string name, bool hasBody, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, name, containingType.Locations[0], (CSharpSyntaxNode)containingType.SyntaxReferences[0].GetSyntax(), MethodKind.Ordinary, isIterator: false, isExtensionMethod: false, isPartial: false, hasBody: hasBody, isNullableAnalysisEnabled: false, diagnostics) { _memberOffset = memberOffset; } protected sealed override bool HasAnyBody => true; internal sealed override bool IsExpressionBodied => false; public sealed override bool IsImplicitlyDeclared => true; protected sealed override Location ReturnTypeLocation => Locations[0]; protected sealed override MethodSymbol? FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) => null; internal sealed override LexicalSortKey GetLexicalSortKey() => LexicalSortKey.GetSynthesizedMemberKey(_memberOffset); protected sealed override ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) => ImmutableArray<TypeParameterSymbol>.Empty; public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; protected sealed override void PartialMethodChecks(BindingDiagnosticBag diagnostics) { } protected sealed override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) { } protected sealed override void CompleteAsyncMethodChecksBetweenStartAndFinish() { } protected sealed override TypeSymbol? ExplicitInterfaceType => null; protected sealed override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { } protected sealed override SourceMemberMethodSymbol? BoundAttributesSource => null; internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() => OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); public sealed override string? GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default) => null; public sealed override bool IsVararg => false; public sealed override RefKind RefKind => RefKind.None; internal sealed override bool GenerateDebugInfo => false; internal sealed override bool SynthesizesLoweredBoundBody => 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.Collections.Immutable; using System.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Common base for ordinary methods synthesized by compiler for records. /// </summary> internal abstract class SynthesizedRecordOrdinaryMethod : SourceOrdinaryMethodSymbolBase { private readonly int _memberOffset; protected SynthesizedRecordOrdinaryMethod(SourceMemberContainerTypeSymbol containingType, string name, bool isReadOnly, bool hasBody, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, name, containingType.Locations[0], (CSharpSyntaxNode)containingType.SyntaxReferences[0].GetSyntax(), MethodKind.Ordinary, isIterator: false, isExtensionMethod: false, isPartial: false, isReadOnly: isReadOnly, hasBody: hasBody, isNullableAnalysisEnabled: false, diagnostics) { _memberOffset = memberOffset; } protected sealed override bool HasAnyBody => true; internal sealed override bool IsExpressionBodied => false; public sealed override bool IsImplicitlyDeclared => true; protected sealed override Location ReturnTypeLocation => Locations[0]; protected sealed override MethodSymbol? FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) => null; internal sealed override LexicalSortKey GetLexicalSortKey() => LexicalSortKey.GetSynthesizedMemberKey(_memberOffset); protected sealed override ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) => ImmutableArray<TypeParameterSymbol>.Empty; public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; protected sealed override void PartialMethodChecks(BindingDiagnosticBag diagnostics) { } protected sealed override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) { } protected sealed override void CompleteAsyncMethodChecksBetweenStartAndFinish() { } protected sealed override TypeSymbol? ExplicitInterfaceType => null; protected sealed override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { } protected sealed override SourceMemberMethodSymbol? BoundAttributesSource => null; internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() => OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); public sealed override string? GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default) => null; public sealed override bool IsVararg => false; public sealed override RefKind RefKind => RefKind.None; internal sealed override bool GenerateDebugInfo => false; internal sealed override bool SynthesizesLoweredBoundBody => true; } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./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(); 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); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; 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, IEnumerable<Symbol> userDefinedMembers, int memberOffset, BindingDiagnosticBag diagnostics) : base( containingType, WellKnownMemberNames.PrintMembersMethodName, isReadOnly: IsReadOnly(containingType, userDefinedMembers), hasBody: true, memberOffset: 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 (!IsPublicInstanceMember(m)) { return false; } if (m.Kind is SymbolKind.Field) { return true; } if (m.Kind is SymbolKind.Property) { var property = (PropertySymbol)m; return IsPrintableProperty(property); } 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); } } private static bool IsReadOnly(NamedTypeSymbol containingType, IEnumerable<Symbol> userDefinedMembers) { return containingType.IsReadOnly || (containingType.IsRecordStruct && AreAllPrintablePropertyGettersReadOnly(userDefinedMembers)); } private static bool AreAllPrintablePropertyGettersReadOnly(IEnumerable<Symbol> members) { foreach (var member in members) { if (member.Kind != SymbolKind.Property) { continue; } var property = (PropertySymbol)member; if (!IsPublicInstanceMember(property) || !IsPrintableProperty(property)) { continue; } var getterMethod = property.GetMethod; if (property.GetMethod is not null && !getterMethod.IsEffectivelyReadOnly) { return false; } } return true; } private static bool IsPublicInstanceMember(Symbol m) { return m.DeclaredAccessibility == Accessibility.Public && !m.IsStatic; } private static bool IsPrintableProperty(PropertySymbol property) { return !property.IsIndexer && !property.IsOverride && property.GetMethod is not null; } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordToString.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The record includes a synthesized override of object.ToString(). /// For `record R(int I) { public int J; }` it prints `R { I = ..., J = ... }`. /// /// The method can be declared explicitly. It is an error if the explicit /// declaration does not match the expected signature or accessibility, or /// if the explicit declaration doesn't allow overriding it in a derived type and /// the record type is not sealed. /// It is an error if either synthesized or explicitly declared method doesn't /// override `object.ToString()` (for example, due to shadowing in intermediate base types, etc.). /// </summary> internal sealed class SynthesizedRecordToString : SynthesizedRecordObjectMethod { private readonly MethodSymbol _printMethod; public SynthesizedRecordToString(SourceMemberContainerTypeSymbol containingType, MethodSymbol printMethod, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.ObjectToString, memberOffset, diagnostics) { Debug.Assert(printMethod is object); _printMethod = printMethod; } protected override SpecialMember OverriddenSpecialMember => SpecialMember.System_Object__ToString; 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_String, location, diagnostics), annotation), Parameters: ImmutableArray<ParameterSymbol>.Empty, IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 0; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.SyntaxNode, compilationState, diagnostics); try { CSharpCompilation compilation = ContainingType.DeclaringCompilation; var stringBuilder = F.WellKnownType(WellKnownType.System_Text_StringBuilder); var stringBuilderCtor = F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__ctor); var builderLocalSymbol = F.SynthesizedLocal(stringBuilder); BoundLocal builderLocal = F.Local(builderLocalSymbol); var block = ArrayBuilder<BoundStatement>.GetInstance(); // var builder = new StringBuilder(); block.Add(F.Assignment(builderLocal, F.New(stringBuilderCtor))); // builder.Append(<name>); block.Add(makeAppendString(F, builderLocal, ContainingType.Name)); // builder.Append(" { "); block.Add(makeAppendString(F, builderLocal, " { ")); // if (this.PrintMembers(builder)) builder.Append(' '); block.Add(F.If(F.Call(F.This(), _printMethod, builderLocal), makeAppendChar(F, builderLocal, ' '))); // builder.Append('}'); block.Add(makeAppendChar(F, builderLocal, '}')); // return builder.ToString(); block.Add(F.Return(F.Call(builderLocal, F.SpecialMethod(SpecialMember.System_Object__ToString)))); F.CloseMethod(F.Block(ImmutableArray.Create(builderLocalSymbol), block.ToImmutableAndFree())); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } static BoundStatement makeAppendString(SyntheticBoundNodeFactory F, BoundLocal builder, string value) { return F.ExpressionStatement(F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendString), F.StringLiteral(value))); } static BoundStatement makeAppendChar(SyntheticBoundNodeFactory F, BoundLocal builder, char value) { return F.ExpressionStatement(F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendChar), F.CharLiteral(value))); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The record includes a synthesized override of object.ToString(). /// For `record R(int I) { public int J; }` it prints `R { I = ..., J = ... }`. /// /// The method can be declared explicitly. It is an error if the explicit /// declaration does not match the expected signature or accessibility, or /// if the explicit declaration doesn't allow overriding it in a derived type and /// the record type is not sealed. /// It is an error if either synthesized or explicitly declared method doesn't /// override `object.ToString()` (for example, due to shadowing in intermediate base types, etc.). /// </summary> internal sealed class SynthesizedRecordToString : SynthesizedRecordObjectMethod { private readonly MethodSymbol _printMethod; public SynthesizedRecordToString(SourceMemberContainerTypeSymbol containingType, MethodSymbol printMethod, int memberOffset, bool isReadOnly, BindingDiagnosticBag diagnostics) : base( containingType, WellKnownMemberNames.ObjectToString, memberOffset, isReadOnly: isReadOnly, diagnostics) { Debug.Assert(printMethod is object); _printMethod = printMethod; } protected override SpecialMember OverriddenSpecialMember => SpecialMember.System_Object__ToString; 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_String, location, diagnostics), annotation), Parameters: ImmutableArray<ParameterSymbol>.Empty, IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 0; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.SyntaxNode, compilationState, diagnostics); try { CSharpCompilation compilation = ContainingType.DeclaringCompilation; var stringBuilder = F.WellKnownType(WellKnownType.System_Text_StringBuilder); var stringBuilderCtor = F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__ctor); var builderLocalSymbol = F.SynthesizedLocal(stringBuilder); BoundLocal builderLocal = F.Local(builderLocalSymbol); var block = ArrayBuilder<BoundStatement>.GetInstance(); // var builder = new StringBuilder(); block.Add(F.Assignment(builderLocal, F.New(stringBuilderCtor))); // builder.Append(<name>); block.Add(makeAppendString(F, builderLocal, ContainingType.Name)); // builder.Append(" { "); block.Add(makeAppendString(F, builderLocal, " { ")); // if (this.PrintMembers(builder)) builder.Append(' '); block.Add(F.If(F.Call(F.This(), _printMethod, builderLocal), makeAppendChar(F, builderLocal, ' '))); // builder.Append('}'); block.Add(makeAppendChar(F, builderLocal, '}')); // return builder.ToString(); block.Add(F.Return(F.Call(builderLocal, F.SpecialMethod(SpecialMember.System_Object__ToString)))); F.CloseMethod(F.Block(ImmutableArray.Create(builderLocalSymbol), block.ToImmutableAndFree())); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } static BoundStatement makeAppendString(SyntheticBoundNodeFactory F, BoundLocal builder, string value) { return F.ExpressionStatement(F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendString), F.StringLiteral(value))); } static BoundStatement makeAppendChar(SyntheticBoundNodeFactory F, BoundLocal builder, char value) { return F.ExpressionStatement(F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendChar), F.CharLiteral(value))); } } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Test/Semantic/Semantics/RecordStructTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.RecordStructs)] public class RecordStructTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); private CompilationVerifier CompileAndVerify( CSharpTestSource src, string? expectedOutput = null, IEnumerable<MetadataReference>? references = null) => base.CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.RegularPreview, references: references, // init-only is unverifiable verify: Verification.Skipped); [Fact] public void StructRecord1() { var src = @" record struct Point(int X, int Y);"; var verifier = CompileAndVerify(src).VerifyDiagnostics(); verifier.VerifyIL("Point.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""Point"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""Point"" IL_000f: call ""bool Point.Equals(Point)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("Point.Equals(Point)", @" { // Code size 49 (0x31) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int Point.<X>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int Point.<X>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_002f IL_0018: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""int Point.<Y>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""int Point.<Y>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002e: ret IL_002f: ldc.i4.0 IL_0030: ret }"); } [Fact] public void StructRecord2() { var src = @" using System; record struct S(int X, int Y) { public static void Main() { var s1 = new S(0, 1); var s2 = new S(0, 1); Console.WriteLine(s1.X); Console.WriteLine(s1.Y); Console.WriteLine(s1.Equals(s2)); Console.WriteLine(s1.Equals(new S(1, 0))); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 True False").VerifyDiagnostics(); } [Fact] public void StructRecord3() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) => false; public static void Main() { var s1 = new S(0, 1); Console.WriteLine(s1.Equals(s1)); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"False") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); verifier.VerifyIL("S.Main", @" { // Code size 23 (0x17) .maxstack 3 .locals init (S V_0) //s1 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""S..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloc.0 IL_000c: call ""bool S.Equals(S)"" IL_0011: call ""void System.Console.WriteLine(bool)"" IL_0016: ret }"); } [Fact] public void StructRecord5() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) { Console.Write(""s""); return true; } public static void Main() { var s1 = new S(0, 1); s1.Equals((object)s1); s1.Equals(s1); } }"; CompileAndVerify(src, expectedOutput: @"ss") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); } [Fact] public void StructRecordDefaultCtor() { const string src = @" public record struct S(int X);"; const string src2 = @" class C { public S M() => new S(); }"; var comp = CreateCompilation(src + src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src); var comp2 = CreateCompilation(src2, references: new[] { comp.EmitToImageReference() }); comp2.VerifyDiagnostics(); } [Fact] public void Equality_01() { var source = @"using static System.Console; record struct S; class Program { static void Main() { var x = new S(); var y = new S(); WriteLine(x.Equals(y)); WriteLine(((object)x).Equals(y)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True True").VerifyDiagnostics(); verifier.VerifyIL("S.Equals(S)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("S.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""S"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""S"" IL_000f: call ""bool S.Equals(S)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); } [Fact] public void RecordStructLanguageVersion() { var src1 = @" struct Point(int x, int y); "; var src2 = @" record struct Point { } "; var src3 = @" record struct Point(int x, int y); "; var comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void RecordStructLanguageVersion_Nested() { var src1 = @" class C { struct Point(int x, int y); } "; var src2 = @" class D { record struct Point { } } "; var src3 = @" struct E { record struct Point(int x, int y); } "; var src4 = @" namespace NS { record struct Point { } } "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src1); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); comp = CreateCompilation(src4); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_IsStruct() { var src = @" record struct Point(int x, int y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.Equal("Point", point.ToTestDisplayString()); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); Assert.Equal("record struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); Assert.Equal("struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } } } [Fact] public void TypeDeclaration_IsStruct_InConstraints() { var src = @" record struct Point(int x, int y); class C<T> where T : struct { void M(C<Point> c) { } } class C2<T> where T : new() { void M(C2<Point> c) { } } class C3<T> where T : class { void M(C3<Point> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (16,22): error CS0452: The type 'Point' must be a reference type in order to use it as parameter 'T' in the generic type or method 'C3<T>' // void M(C3<Point> c) { } // 1 Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "c").WithArguments("C3<T>", "T", "Point").WithLocation(16, 22) ); } [Fact] public void TypeDeclaration_IsStruct_Unmanaged() { var src = @" record struct Point(int x, int y); record struct Point2(string x, string y); class C<T> where T : unmanaged { void M(C<Point> c) { } void M2(C<Point2> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,23): error CS8377: The type 'Point2' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C<T>' // void M2(C<Point2> c) { } // 1 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("C<T>", "T", "Point2").WithLocation(8, 23) ); } [Fact] public void IsRecord_Generic() { var src = @" record struct Point<T>(T x, T y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); } } } [Fact] public void IsRecord_Retargeting() { var src = @" public record struct Point(int x, int y); "; var comp = CreateCompilation(src, targetFramework: TargetFramework.Mscorlib40); var comp2 = CreateCompilation("", targetFramework: TargetFramework.Mscorlib46, references: new[] { comp.ToMetadataReference() }); var point = comp2.GlobalNamespace.GetTypeMember("Point"); Assert.Equal("Point", point.ToTestDisplayString()); Assert.IsType<RetargetingNamedTypeSymbol>(point); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } [Fact] public void IsRecord_AnonymousType() { var src = @" class C { void M() { var x = new { X = 1 }; } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var creation = tree.GetRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>().Single(); var type = model.GetTypeInfo(creation).Type!; Assert.Equal("<anonymous type: System.Int32 X>", type.ToTestDisplayString()); Assert.IsType<AnonymousTypeManager.AnonymousTypePublicSymbol>(((Symbols.PublicModel.NonErrorNamedTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_ErrorType() { var src = @" class C { Error M() => throw null; } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("Error", type.ToTestDisplayString()); Assert.IsType<ExtendedErrorTypeSymbol>(((Symbols.PublicModel.ErrorTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Pointer() { var src = @" class C { int* M() => throw null; } "; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("System.Int32*", type.ToTestDisplayString()); Assert.IsType<PointerTypeSymbol>(((Symbols.PublicModel.PointerTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Dynamic() { var src = @" class C { void M(dynamic d) { } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.GetParameterType(0); Assert.Equal("dynamic", type.ToTestDisplayString()); Assert.IsType<DynamicTypeSymbol>(((Symbols.PublicModel.DynamicTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void TypeDeclaration_MayNotHaveBaseType() { var src = @" record struct Point(int x, int y) : object; record struct Point2(int x, int y) : System.ValueType; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,37): error CS0527: Type 'object' in interface list is not an interface // record struct Point(int x, int y) : object; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "object").WithArguments("object").WithLocation(2, 37), // (3,38): error CS0527: Type 'ValueType' in interface list is not an interface // record struct Point2(int x, int y) : System.ValueType; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "System.ValueType").WithArguments("System.ValueType").WithLocation(3, 38) ); } [Fact] public void TypeDeclaration_MayNotHaveTypeConstraintsWithoutTypeParameters() { var src = @" record struct Point(int x, int y) where T : struct; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,35): error CS0080: Constraints are not allowed on non-generic declarations // record struct Point(int x, int y) where T : struct; Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(2, 35) ); } [Fact] public void TypeDeclaration_AllowedModifiers() { var src = @" readonly partial record struct S1; public record struct S2; internal record struct S3; public class Base { public int S6; } public class C : Base { private protected record struct S4; protected internal record struct S5; new record struct S6; } unsafe record struct S7; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics(); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S1").DeclaredAccessibility); Assert.Equal(Accessibility.Public, comp.GlobalNamespace.GetTypeMember("S2").DeclaredAccessibility); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S3").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedAndInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S4").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S5").DeclaredAccessibility); } [Fact] public void TypeDeclaration_DisallowedModifiers() { var src = @" abstract record struct S1; volatile record struct S2; extern record struct S3; virtual record struct S4; override record struct S5; async record struct S6; ref record struct S7; unsafe record struct S8; static record struct S9; sealed record struct S10; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS0106: The modifier 'abstract' is not valid for this item // abstract record struct S1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S1").WithArguments("abstract").WithLocation(2, 24), // (3,24): error CS0106: The modifier 'volatile' is not valid for this item // volatile record struct S2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S2").WithArguments("volatile").WithLocation(3, 24), // (4,22): error CS0106: The modifier 'extern' is not valid for this item // extern record struct S3; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S3").WithArguments("extern").WithLocation(4, 22), // (5,23): error CS0106: The modifier 'virtual' is not valid for this item // virtual record struct S4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S4").WithArguments("virtual").WithLocation(5, 23), // (6,24): error CS0106: The modifier 'override' is not valid for this item // override record struct S5; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S5").WithArguments("override").WithLocation(6, 24), // (7,21): error CS0106: The modifier 'async' is not valid for this item // async record struct S6; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S6").WithArguments("async").WithLocation(7, 21), // (8,19): error CS0106: The modifier 'ref' is not valid for this item // ref record struct S7; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S7").WithArguments("ref").WithLocation(8, 19), // (9,22): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe record struct S8; Diagnostic(ErrorCode.ERR_IllegalUnsafe, "S8").WithLocation(9, 22), // (10,22): error CS0106: The modifier 'static' is not valid for this item // static record struct S9; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S9").WithArguments("static").WithLocation(10, 22), // (11,22): error CS0106: The modifier 'sealed' is not valid for this item // sealed record struct S10; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S10").WithArguments("sealed").WithLocation(11, 22) ); } [Fact] public void TypeDeclaration_DuplicatesModifiers() { var src = @" public public record struct S2; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): error CS1004: Duplicate 'public' modifier // public public record struct S2; Diagnostic(ErrorCode.ERR_DuplicateModifier, "public").WithArguments("public").WithLocation(2, 8) ); } [Fact] public void TypeDeclaration_BeforeTopLevelStatement() { var src = @" record struct S; System.Console.WriteLine(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine();").WithLocation(3, 1) ); } [Fact] public void TypeDeclaration_WithTypeParameters() { var src = @" S<string> local = default; local.ToString(); record struct S<T>; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); Assert.Equal(new[] { "T" }, comp.GlobalNamespace.GetTypeMember("S").TypeParameters.ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_AllowedModifiersForMembers() { var src = @" record struct S { protected int Property { get; set; } // 1 internal protected string field; // 2, 3 abstract void M(); // 4 virtual void M2() { } // 5 }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0666: 'S.Property': new protected member declared in struct // protected int Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Property").WithArguments("S.Property").WithLocation(4, 19), // (5,31): error CS0666: 'S.field': new protected member declared in struct // internal protected string field; // 2, 3 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "field").WithArguments("S.field").WithLocation(5, 31), // (5,31): warning CS0649: Field 'S.field' is never assigned to, and will always have its default value null // internal protected string field; // 2, 3 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("S.field", "null").WithLocation(5, 31), // (6,19): error CS0621: 'S.M()': virtual or abstract members cannot be private // abstract void M(); // 4 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M").WithArguments("S.M()").WithLocation(6, 19), // (7,18): error CS0621: 'S.M2()': virtual or abstract members cannot be private // virtual void M2() { } // 5 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M2").WithArguments("S.M2()").WithLocation(7, 18) ); } [Fact] public void TypeDeclaration_ImplementInterface() { var src = @" I i = (I)default(S); System.Console.Write(i.M(""four"")); I i2 = (I)default(S2); System.Console.Write(i2.M(""four"")); interface I { int M(string s); } public record struct S : I { public int M(string s) => s.Length; } public record struct S2 : I { int I.M(string s) => s.Length + 1; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "45"); AssertEx.Equal(new[] { "System.Int32 S.M(System.String s)", "System.String S.ToString()", "System.Boolean S.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean S.op_Inequality(S left, S right)", "System.Boolean S.op_Equality(S left, S right)", "System.Int32 S.GetHashCode()", "System.Boolean S.Equals(System.Object obj)", "System.Boolean S.Equals(S other)", "S..ctor()" }, comp.GetMember<NamedTypeSymbol>("S").GetMembers().ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_SatisfiesStructConstraint() { var src = @" S s = default; System.Console.Write(M(s)); static int M<T>(T t) where T : struct, I => t.Property; public interface I { int Property { get; } } public record struct S : I { public int Property => 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void TypeDeclaration_AccessingThis() { var src = @" S s = new S(); System.Console.Write(s.M()); public record struct S { public int Property => 42; public int M() => this.Property; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("S.M", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int S.Property.get"" IL_0006: ret } "); } [Fact] public void TypeDeclaration_NoBaseInitializer() { var src = @" public record struct S { public S(int i) : base() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,12): error CS0522: 'S': structs cannot call base class constructors // public S(int i) : base() { } Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, "S").WithArguments("S").WithLocation(4, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_01() { var src = @"record struct S0(); record struct S1; record struct S2 { public S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S0(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8), // (3,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(3, 8), // (5,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // public S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(5, 12)); var verifier = CompileAndVerify(src); verifier.VerifyIL("S0..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); verifier.VerifyMissing("S1..ctor()"); verifier.VerifyIL("S2..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [Fact] public void TypeDeclaration_ParameterlessConstructor_02() { var src = @"record struct S1 { S1() { } } record struct S2 { internal S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (3,5): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // S1() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S1").WithArguments("parameterless struct constructors", "10.0").WithLocation(3, 5), // (3,5): error CS8938: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (5,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(5, 8), // (7,14): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // internal S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(7, 14), // (7,14): error CS8938: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,5): error CS8918: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (7,14): error CS8918: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); } [Fact] public void TypeDeclaration_ParameterlessConstructor_OtherConstructors() { var src = @" record struct S1 { public S1() { } S1(object o) { } // ok because no record parameter list } record struct S2 { S2(object o) { } } record struct S3() { S3(object o) { } // 1 } record struct S4() { S4(object o) : this() { } } record struct S5(object o) { public S5() { } // 2 } record struct S6(object o) { public S6() : this(null) { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // S3(object o) { } // 1 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S3").WithLocation(13, 5), // (21,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public S5() { } // 2 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S5").WithLocation(21, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_Initializers() { var src = @" var s1 = new S1(); var s2 = new S2(null); var s2b = new S2(); var s3 = new S3(); var s4 = new S4(new object()); var s5 = new S5(); var s6 = new S6(""s6.other""); System.Console.Write((s1.field, s2.field, s2b.field is null, s3.field, s4.field, s5.field, s6.field, s6.other)); record struct S1 { public string field = ""s1""; public S1() { } } record struct S2 { public string field = ""s2""; public S2(object o) { } } record struct S3() { public string field = ""s3""; } record struct S4 { public string field = ""s4""; public S4(object o) : this() { } } record struct S5() { public string field = ""s5""; public S5(object o) : this() { } } record struct S6(string other) { public string field = ""s6.field""; public S6() : this(""ignored"") { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(s1, s2, True, s3, s4, s5, s6.field, s6.other)"); } [Fact] public void TypeDeclaration_InstanceInitializers() { var src = @" public record struct S { public int field = 42; public int Property { get; set; } = 43; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // public record struct S Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 15), // (4,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int field = 42; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "field").WithArguments("struct field initializers", "10.0").WithLocation(4, 16), // (5,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int Property { get; set; } = 43; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Property").WithArguments("struct field initializers", "10.0").WithLocation(5, 16)); comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_NoDestructor() { var src = @" public record struct S { ~S() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,6): error CS0575: Only class types can contain destructors // ~S() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "S").WithArguments("S.~S()").WithLocation(4, 6) ); } [Fact] public void TypeDeclaration_DifferentPartials() { var src = @" partial record struct S1; partial struct S1 { } partial struct S2 { } partial record struct S2; partial record struct S3; partial record S3 { } partial record struct S4; partial record class S4 { } partial record struct S5; partial class S5 { } partial record struct S6; partial interface S6 { } partial record class C1; partial struct C1 { } partial record class C2; partial record struct C2 { } partial record class C3 { } partial record C3; partial record class C4; partial class C4 { } partial record class C5; partial interface C5 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,16): error CS0261: Partial declarations of 'S1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct S1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S1").WithArguments("S1").WithLocation(3, 16), // (6,23): error CS0261: Partial declarations of 'S2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct S2; Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S2").WithArguments("S2").WithLocation(6, 23), // (9,16): error CS0261: Partial declarations of 'S3' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record S3 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S3").WithArguments("S3").WithLocation(9, 16), // (12,22): error CS0261: Partial declarations of 'S4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record class S4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S4").WithArguments("S4").WithLocation(12, 22), // (15,15): error CS0261: Partial declarations of 'S5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class S5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S5").WithArguments("S5").WithLocation(15, 15), // (18,19): error CS0261: Partial declarations of 'S6' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface S6 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S6").WithArguments("S6").WithLocation(18, 19), // (21,16): error CS0261: Partial declarations of 'C1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct C1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C1").WithArguments("C1").WithLocation(21, 16), // (24,23): error CS0261: Partial declarations of 'C2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct C2 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C2").WithArguments("C2").WithLocation(24, 23), // (30,15): error CS0261: Partial declarations of 'C4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class C4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C4").WithArguments("C4").WithLocation(30, 15), // (33,19): error CS0261: Partial declarations of 'C5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface C5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C5").WithArguments("C5").WithLocation(33, 19) ); } [Fact] public void PartialRecord_OnlyOnePartialHasParameterList() { var src = @" partial record struct S(int i); partial record struct S(int i); partial record struct S2(int i); partial record struct S2(); partial record struct S3(); partial record struct S3(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,24): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S(int i); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int i)").WithLocation(3, 24), // (6,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S2(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(6, 25), // (9,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S3(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(9, 25) ); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record struct C(int X) { public int P1 { get; set; } = X; } public partial record struct C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */) .VerifyDiagnostics( // (5,30): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'C'. To specify an ordering, all instance fields must be in the same declaration. // public partial record struct C(int X) Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "C").WithArguments("C").WithLocation(5, 30) ); } [Fact] public void PartialRecord_DuplicateMemberNames() { var src = @" public partial record struct C(int X) { public void M(int i) { } } public partial record struct C { public void M(string s) { } } "; var comp = CreateCompilation(src); var expectedMemberNames = new string[] { ".ctor", "<X>k__BackingField", "get_X", "set_X", "X", "M", "M", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "Deconstruct", ".ctor", }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordInsideGenericType() { var src = @" var c = new C<int>.Nested(2); System.Console.Write(c.T); public class C<T> { public record struct Nested(T T); } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void PositionalMemberModifiers_RefOrOut() { var src = @" record struct R(ref int P1, out int P2); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,15): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 15), // (2,17): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 17), // (2,29): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 29) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_This() { var src = @" record struct R(this int i); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0027: Keyword 'this' is not available in the current context // record struct R(this int i); Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 17) ); } [Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")] public void Clone_DisallowedInSource() { var src = @" record struct C1(string Clone); // 1 record struct C2 { string Clone; // 2 } record struct C3 { string Clone { get; set; } // 3 } record struct C5 { void Clone() { } // 4 void Clone(int i) { } // 5 } record struct C6 { class Clone { } // 6 } record struct C7 { delegate void Clone(); // 7 } record struct C8 { event System.Action Clone; // 8 } record struct Clone { Clone(int i) => throw null; } record struct C9 : System.ICloneable { object System.ICloneable.Clone() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,25): error CS8859: Members named 'Clone' are disallowed in records. // record struct C1(string Clone); // 1 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 25), // (5,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone; // 2 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(5, 12), // (5,12): warning CS0169: The field 'C2.Clone' is never used // string Clone; // 2 Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C2.Clone").WithLocation(5, 12), // (9,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone { get; set; } // 3 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(9, 12), // (13,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone() { } // 4 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 10), // (14,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone(int i) { } // 5 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(14, 10), // (18,11): error CS8859: Members named 'Clone' are disallowed in records. // class Clone { } // 6 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 11), // (22,19): error CS8859: Members named 'Clone' are disallowed in records. // delegate void Clone(); // 7 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 19), // (26,25): error CS8859: Members named 'Clone' are disallowed in records. // event System.Action Clone; // 8 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 25), // (26,25): warning CS0067: The event 'C8.Clone' is never used // event System.Action Clone; // 8 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(26, 25) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes() { var src = @" class C<T> { } static class C2 { } ref struct RefLike{} unsafe record struct C( // 1 int* P1, // 2 int*[] P2, // 3 C<int*[]> P3, delegate*<int, int> P4, // 4 void P5, // 5 C2 P6, // 6, 7 System.ArgIterator P7, // 8 System.TypedReference P8, // 9 RefLike P9); // 10 "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (6,22): error CS0721: 'C2': static types cannot be used as parameters // unsafe record struct C( // 1 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 22), // (7,10): error CS8908: The type 'int*' may not be used for a field of a record. // int* P1, // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P1").WithArguments("int*").WithLocation(7, 10), // (8,12): error CS8908: The type 'int*[]' may not be used for a field of a record. // int*[] P2, // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P2").WithArguments("int*[]").WithLocation(8, 12), // (10,25): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // delegate*<int, int> P4, // 4 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P4").WithArguments("delegate*<int, int>").WithLocation(10, 25), // (11,5): error CS1536: Invalid parameter type 'void' // void P5, // 5 Diagnostic(ErrorCode.ERR_NoVoidParameter, "void").WithLocation(11, 5), // (12,8): error CS0722: 'C2': static types cannot be used as return types // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (12,8): error CS0721: 'C2': static types cannot be used as parameters // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (13,5): error CS0610: Field or property cannot be of type 'ArgIterator' // System.ArgIterator P7, // 8 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 5), // (14,5): error CS0610: Field or property cannot be of type 'TypedReference' // System.TypedReference P8, // 9 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 5), // (15,5): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // RefLike P9); // 10 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 5) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record struct C { public int* f1; // 1 public int*[] f2; // 2 public C<int*[]> f3; public delegate*<int, int> f4; // 3 public void f5; // 4 public C2 f6; // 5 public System.ArgIterator f7; // 6 public System.TypedReference f8; // 7 public RefLike f9; // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1; // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2; // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4; // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,12): error CS0670: Field cannot have void type // public void f5; // 4 Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(12, 12), // (13,15): error CS0723: Cannot declare a variable of static type 'C2' // public C2 f6; // 5 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(13, 15), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7; // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8; // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9; // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers_AutoProperties() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record struct C { public int* f1 { get; set; } // 1 public int*[] f2 { get; set; } // 2 public C<int*[]> f3 { get; set; } public delegate*<int, int> f4 { get; set; } // 3 public void f5 { get; set; } // 4 public C2 f6 { get; set; } // 5, 6 public System.ArgIterator f7 { get; set; } // 6 public System.TypedReference f8 { get; set; } // 7 public RefLike f9 { get; set; } // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1 { get; set; } // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2 { get; set; } // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4 { get; set; } // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,17): error CS0547: 'C.f5': property or indexer cannot have void type // public void f5 { get; set; } // 4 Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "f5").WithArguments("C.f5").WithLocation(12, 17), // (13,20): error CS0722: 'C2': static types cannot be used as return types // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("C2").WithLocation(13, 20), // (13,25): error CS0721: 'C2': static types cannot be used as parameters // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("C2").WithLocation(13, 25), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7 { get; set; } // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8 { get; set; } // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9 { get; set; } // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [Fact] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_PointerTypeAllowedForParameterAndProperty() { var src = @" class C<T> { } unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) { int* P1 { get { System.Console.Write(""P1 ""); return null; } init { } } int*[] P2 { get { System.Console.Write(""P2 ""); return null; } init { } } C<int*[]> P3 { get { System.Console.Write(""P3 ""); return null; } init { } } public unsafe static void Main() { var x = new C(null, null, null); var (x1, x2, x3) = x; System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugExe); comp.VerifyEmitDiagnostics( // (4,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 29), // (4,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 40), // (4,54): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 54) ); CompileAndVerify(comp, expectedOutput: "P1 P2 P3 RAN", verify: Verification.Skipped /* pointers */); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_StaticFields() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public static int* f1; public static int*[] f2; public static C<int*[]> f3; public static delegate*<int, int> f4; public static C2 f6; // 1 public static System.ArgIterator f7; // 2 public static System.TypedReference f8; // 3 public static RefLike f9; // 4 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (12,22): error CS0723: Cannot declare a variable of static type 'C2' // public static C2 f6; // 1 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(12, 22), // (13,19): error CS0610: Field or property cannot be of type 'ArgIterator' // public static System.ArgIterator f7; // 2 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 19), // (14,19): error CS0610: Field or property cannot be of type 'TypedReference' // public static System.TypedReference f8; // 3 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 19), // (15,19): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public static RefLike f9; // 4 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 19) ); } [Fact] public void RecordProperties_01() { var src = @" using System; record struct C(int X, int Y) { int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 26 (0x1a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4 0x159 IL_0014: stfld ""int C.Z"" IL_0019: ret } "); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.False(c.IsReadOnly); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("readonly System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void C.X.set", x.SetMethod.ToTestDisplayString()); Assert.False(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.False(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_01_EmptyParameterList() { var src = @" using System; record struct C() { int Z = 345; public static void Main() { var c = new C(); Console.Write(c.Z); } }"; CreateCompilation(src).VerifyEmitDiagnostics(); } [Fact] public void RecordProperties_01_Readonly() { var src = @" using System; readonly record struct C(int X, int Y) { readonly int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.True(c.IsReadOnly); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", x.SetMethod.ToTestDisplayString()); Assert.True(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.True(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_01_ReadonlyMismatch() { var src = @" readonly record struct C(int X) { public int X { get; set; } = X; // 1 } record struct C2(int X) { public int X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,16): error CS8341: Auto-implemented instance properties in readonly structs must be readonly. // public int X { get; set; } = X; // 1 Diagnostic(ErrorCode.ERR_AutoPropsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void RecordProperties_02() { var src = @" using System; record struct C(int X, int Y) { public C(int a, int b) { } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } private int X1 = X; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C(int a, int b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(5, 12), // (5,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, int b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(5, 12), // (11,21): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(int, int)' and 'C.C(int, int)' // var c = new C(1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "C").WithArguments("C.C(int, int)", "C.C(int, int)").WithLocation(11, 21) ); } [Fact] public void RecordProperties_03() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,15): error CS0843: Auto-implemented property 'C.X' must be fully assigned before control is returned to the caller. // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C").WithArguments("C.X").WithLocation(3, 15), // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_03_InitializedWithY() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = Y; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "22") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_04() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = 3; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "32") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_05() { var src = @" record struct C(int X, int X) { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,28): error CS0100: The parameter name 'X' is a duplicate // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 28), // (2,28): error CS0102: The type 'C' already contains a definition for 'X' // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 28) ); var expectedMembers = new[] { "System.Int32 C.X { get; set; }", "System.Int32 C.X { get; set; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "Deconstruct", ".ctor" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_06() { var src = @" record struct C(int X, int Y) { public void get_X() { } public void set_X() { } int get_Y(int value) => value; int set_Y(int value) => value; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 21), // (2,28): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 28) ); var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Int32 C.<X>k__BackingField", "readonly System.Int32 C.X.get", "void C.X.set", "System.Int32 C.X { get; set; }", "System.Int32 C.<Y>k__BackingField", "readonly System.Int32 C.Y.get", "void C.Y.set", "System.Int32 C.Y { get; set; }", "void C.get_X()", "void C.set_X()", "System.Int32 C.get_Y(System.Int32 value)", "System.Int32 C.set_Y(System.Int32 value)", "System.String C.ToString()", "System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object obj)", "System.Boolean C.Equals(C other)", "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", "C..ctor()", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void RecordProperties_07() { var comp = CreateCompilation(@" record struct C1(object P, object get_P); record struct C2(object get_P, object P);"); comp.VerifyDiagnostics( // (2,25): error CS0102: The type 'C1' already contains a definition for 'get_P' // record struct C1(object P, object get_P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 25), // (3,39): error CS0102: The type 'C2' already contains a definition for 'get_P' // record struct C2(object get_P, object P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 39) ); } [Fact] public void RecordProperties_08() { var comp = CreateCompilation(@" record struct C1(object O1) { public object O1 { get; } = O1; public object O2 { get; } = O1; }"); comp.VerifyDiagnostics(); } [Fact] public void RecordProperties_09() { var src = @" record struct C(object P1, object P2, object P3, object P4) { class P1 { } object P2 = 2; int P3(object o) => 3; int P4<T>(T t) => 4; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS0102: The type 'C' already contains a definition for 'P1' // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(2, 24), // (2,35): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(2, 35), // (6,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(6, 9), // (7,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(7, 9) ); } [Fact] public void RecordProperties_10() { var src = @" record struct C(object P) { const int P = 4; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record struct C(object P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "object", "P").WithLocation(2, 24), // (2,24): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 24) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter() { var comp = CreateCompilation(@" record struct C1(object O1, object O2, object O3) // 1, 2 { public object O1 { get; init; } public object O2 { get; init; } = M(O2); public object O3 { get; init; } = M(O3 = null); private static object M(object o) => o; } "); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'C1.O1' must be fully assigned before control is returned to the caller. // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C1").WithArguments("C1.O1").WithLocation(2, 15), // (2,25): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 25), // (2,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter_InRefOut() { var comp = CreateCompilation(@" record struct C1(object O1, object O2, object O3) // 1 { public object O1 { get; init; } = MIn(in O1); public object O2 { get; init; } = MRef(ref O2); public object O3 { get; init; } = MOut(out O3); static object MIn(in object o) => o; static object MRef(ref object o) => o; static object MOut(out object o) => throw null; } "); comp.VerifyDiagnostics( // (2,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_SelfContainedStruct() { var comp = CreateCompilation(@" record struct C(C c); "); comp.VerifyDiagnostics( // (2,19): error CS0523: Struct member 'C.c' of type 'C' causes a cycle in the struct layout // record struct C(C c); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "c").WithArguments("C.c", "C").WithLocation(2, 19) ); } [Fact] public void RecordProperties_PropertyInValueType() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); { var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } { var src = @" readonly record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,31): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // readonly record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 31) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } } [Fact] public void RecordProperties_PropertyInValueType_Static() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public static bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): error CS8866: Record member 'System.ValueType.X' must be a readable instance property or field of type 'bool' to match positional parameter 'X'. // record struct C(bool X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("System.ValueType.X", "bool", "X").WithLocation(2, 22), // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); } [Fact] public void StaticCtor() { var src = @" record R(int x) { static void Main() { } static R() { System.Console.Write(""static ctor""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped /* init-only */); } [Fact] public void StaticCtor_ParameterlessPrimaryCtor() { var src = @" record struct R(int I) { static R() { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void StaticCtor_CopyCtor() { var src = @" record struct R(int I) { static R(R r) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0132: 'R.R(R)': a static constructor must be parameterless // static R(R r) { } Diagnostic(ErrorCode.ERR_StaticConstParam, "R").WithArguments("R.R(R)").WithLocation(4, 12) ); } [Fact] public void InterfaceImplementation_NotReadonly() { var source = @" I r = new R(42); r.P2 = 43; r.P3 = 44; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; set; } int P2 { get; set; } int P3 { get; set; } } record struct R(int P1) : I { public int P2 { get; set; } = 0; int I.P3 { get; set; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44)"); } [Fact] public void InterfaceImplementation_NotReadonly_InitOnlyInterface() { var source = @" interface I { int P1 { get; init; } } record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,27): error CS8854: 'R' does not implement interface member 'I.P1.init'. 'R.P1.set' cannot implement 'I.P1.init'. // record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.init", "R.P1.set").WithLocation(6, 27) ); } [Fact] public void InterfaceImplementation_Readonly() { var source = @" I r = new R(42) { P2 = 43 }; System.Console.Write((r.P1, r.P2)); interface I { int P1 { get; init; } int P2 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */); } [Fact] public void InterfaceImplementation_Readonly_SetInterface() { var source = @" interface I { int P1 { get; set; } } readonly record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,36): error CS8854: 'R' does not implement interface member 'I.P1.set'. 'R.P1.init' cannot implement 'I.P1.set'. // readonly record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.set", "R.P1.init").WithLocation(6, 36) ); } [Fact] public void InterfaceImplementation_Readonly_PrivateImplementation() { var source = @" I r = new R(42) { P2 = 43, P3 = 44 }; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; init; } int P2 { get; init; } int P3 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; int I.P3 { get; init; } = 0; // not practically initializable } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,28): error CS0117: 'R' does not contain a definition for 'P3' // I r = new R(42) { P2 = 43, P3 = 44 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "P3").WithArguments("R", "P3").WithLocation(2, 28) ); } [Fact] public void Initializers_01() { var src = @" using System; record struct C(int X) { int Z = X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Single(); Assert.Equal("C", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); } [Fact] public void Initializers_02() { var src = @" record struct C(int X) { static int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,20): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // static int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 20) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; set; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_03() { var src = @" record struct C(int X) { const int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // const int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; set; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_04() { var src = @" using System; record struct C(int X) { Func<int> Z = () => X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("() => X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("lambda expression", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void SynthesizedRecordPointerProperty() { var src = @" record struct R(int P1, int* P2, delegate*<int> P3);"; var comp = CreateCompilation(src); var p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P1"); Assert.False(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P2"); Assert.True(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P3"); Assert.True(p.HasPointerType); } [Fact] public void PositionalMemberModifiers_In() { var src = @" var r = new R(42); int i = 43; var r2 = new R(in i); System.Console.Write((r.P1, r2.P1)); record struct R(in int P1); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "(42, 43)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(in System.Int32 P1)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberModifiers_Params() { var src = @" var r = new R(42, 43); var r2 = new R(new[] { 44, 45 }); System.Console.Write((r.Array[0], r.Array[1], r2.Array[0], r2.Array[1])); record struct R(params int[] Array); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(params System.Int32[] Array)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberDefaultValue() { var src = @" var r = new R(); // This uses the parameterless constructor System.Console.Write(r.P); record struct R(int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "0"); } [Fact] public void PositionalMemberDefaultValue_PassingOneArgument() { var src = @" var r = new R(41); System.Console.Write(r.O); System.Console.Write("" ""); System.Console.Write(r.P); record struct R(int O, int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "41 42"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 1) { public int P { get; init; } = 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,28): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int O, int P = 1) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(5, 28) ); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldc.i4.s 42 IL_000a: stfld ""int R.<P>k__BackingField"" IL_000f: ret }"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer() { var src = @" record struct R(int P = 42) { public int P { get; init; } public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'R.P' must be fully assigned before control is returned to the caller. // record struct R(int P = 42) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "R").WithArguments("R.P").WithLocation(2, 15), // (2,21): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int P = 42) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 21) ); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 42) { public int P { get; init; } = P; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int R.<P>k__BackingField"" IL_000e: ret }"); } [Fact] public void RecordWithConstraints_NullableWarning() { var src = @" #nullable enable var r = new R<string?>(""R""); var r2 = new R2<string?>(""R2""); System.Console.Write((r.P, r2.P)); record struct R<T>(T P) where T : class; record struct R2<T>(T P) where T : class { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,15): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r = new R<string?>("R"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R<T>", "T", "string?").WithLocation(3, 15), // (4,17): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r2 = new R2<string?>("R2"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R2<T>", "T", "string?").WithLocation(4, 17) ); CompileAndVerify(comp, expectedOutput: "(R, R2)"); } [Fact] public void RecordWithConstraints_ConstraintError() { var src = @" record struct R<T>(T P) where T : class; record struct R2<T>(T P) where T : class { } public class C { public static void Main() { _ = new R<int>(1); _ = new R2<int>(2); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R<T>' // _ = new R<int>(1); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R<T>", "T", "int").WithLocation(9, 19), // (10,20): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R2<T>' // _ = new R2<int>(2); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R2<T>", "T", "int").WithLocation(10, 20) ); } [Fact] public void CyclicBases4() { var text = @" record struct A<T> : B<A<T>> { } record struct B<T> : A<B<T>> { A<T> F() { return null; } } "; var comp = CreateCompilation(text); comp.GetDeclarationDiagnostics().Verify( // (3,22): error CS0527: Type 'A<B<T>>' in interface list is not an interface // record struct B<T> : A<B<T>> Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "A<B<T>>").WithArguments("A<B<T>>").WithLocation(3, 22), // (2,22): error CS0527: Type 'B<A<T>>' in interface list is not an interface // record struct A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "B<A<T>>").WithArguments("B<A<T>>").WithLocation(2, 22) ); } [Fact] public void PartialClassWithDifferentTupleNamesInImplementedInterfaces() { var source = @" public interface I<T> { } public partial record C1 : I<(int a, int b)> { } public partial record C1 : I<(int notA, int notB)> { } public partial record C2 : I<(int a, int b)> { } public partial record C2 : I<(int, int)> { } public partial record C3 : I<(int a, int b)> { } public partial record C3 : I<(int a, int b)> { } public partial record C4 : I<(int a, int b)> { } public partial record C4 : I<(int b, int a)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,23): error CS8140: 'I<(int notA, int notB)>' is already listed in the interface list on type 'C1' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C1 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I<(int notA, int notB)>", "I<(int a, int b)>", "C1").WithLocation(3, 23), // (6,23): error CS8140: 'I<(int, int)>' is already listed in the interface list on type 'C2' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C2 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C2").WithArguments("I<(int, int)>", "I<(int a, int b)>", "C2").WithLocation(6, 23), // (12,23): error CS8140: 'I<(int b, int a)>' is already listed in the interface list on type 'C4' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C4 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C4").WithArguments("I<(int b, int a)>", "I<(int a, int b)>", "C4").WithLocation(12, 23) ); } [Fact] public void CS0267ERR_PartialMisplaced() { var test = @" partial public record struct C // CS0267 { } "; CreateCompilation(test).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial public record struct C // CS0267 Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1) ); } [Fact] public void SealedStaticRecord() { var source = @" sealed static record struct R; "; CreateCompilation(source).VerifyDiagnostics( // (2,29): error CS0106: The modifier 'sealed' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("sealed").WithLocation(2, 29), // (2,29): error CS0106: The modifier 'static' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 29) ); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" record struct C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(5, 25), // (4,41): error CS0106: The modifier 'abstract' is not valid for this item // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_BadMemberFlag, "E").WithArguments("abstract").WithLocation(4, 41) ); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" public record struct iii { ~iiii(){} } "; CreateCompilation(test).VerifyDiagnostics( // (4,6): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(4, 6), // (4,6): error CS0575: Only class types can contain destructors // ~iiii(){} Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "iiii").WithArguments("iii.~iii()").WithLocation(4, 6) ); } [Fact] public void StaticRecordWithConstructorAndDestructor() { var text = @" static record struct R(int I) { public R() : this(0) { } ~R() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,22): error CS0106: The modifier 'static' is not valid for this item // static record struct R(int I) Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22), // (5,6): error CS0575: Only class types can contain destructors // ~R() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "R").WithArguments("R.~R()").WithLocation(5, 6) ); } [Fact] public void RecordWithPartialMethodExplicitImplementation() { var source = @"record struct R { partial void M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,18): error CS0751: A partial method must be declared within a partial type // partial void M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 18) ); } [Fact] public void RecordWithPartialMethodRequiringBody() { var source = @"partial record struct R { public partial int M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,24): error CS8795: Partial method 'R.M()' must have an implementation part because it has accessibility modifiers. // public partial int M(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M").WithArguments("R.M()").WithLocation(3, 24) ); } [Fact] public void CanDeclareIteratorInRecord() { var source = @" using System.Collections.Generic; foreach(var i in new X(42).GetItems()) { System.Console.Write(i); } public record struct X(int a) { public IEnumerable<int> GetItems() { yield return a; yield return a + 1; } }"; var comp = CreateCompilation(source).VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "4243"); } [Fact] public void ParameterlessConstructor() { var src = @" System.Console.Write(new C().Property); record struct C() { public int Property { get; set; } = 42; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void XmlDoc() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record struct C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] public void XmlDoc_Cref() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for <see cref=""I1""/></param> public record struct C(int I1) { /// <summary>Summary</summary> /// <param name=""x"">Description for <see cref=""x""/></param> public void M(int x) { } } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,52): warning CS1574: XML comment has cref attribute 'x' that could not be resolved // /// <param name="x">Description for <see cref="x"/></param> Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x").WithLocation(7, 52) ); var tree = comp.SyntaxTrees.Single(); var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>(); var cref = docComments.First().DescendantNodes().OfType<XmlCrefAttributeSyntax>().First().Cref; Assert.Equal("I1", cref.ToString()); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal(SymbolKind.Property, model.GetSymbolInfo(cref).Symbol!.Kind); } [Fact] public void Deconstruct_Simple() { var source = @"using System; record struct B(int X, int Y) { public static void Main() { M(new B(1, 2)); } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); var deconstruct = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("B.Deconstruct"); Assert.Equal(2, deconstruct.ParameterCount); Assert.Equal(RefKind.Out, deconstruct.Parameters[0].RefKind); Assert.Equal("X", deconstruct.Parameters[0].Name); Assert.Equal(RefKind.Out, deconstruct.Parameters[1].RefKind); Assert.Equal("Y", deconstruct.Parameters[1].Name); Assert.True(deconstruct.ReturnsVoid); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsStatic); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); } [Fact] public void Deconstruct_PositionalAndNominalProperty() { var source = @"using System; record struct B(int X) { public int Y { get; init; } = 0; public static void Main() { M(new B(1)); } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Nested() { var source = @"using System; record struct B(int X, int Y); record struct C(B B, int Z) { public static void Main() { M(new C(new B(1, 2), 3)); } static void M(C c) { switch (c) { case C(B(int x, int y), int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly B C.B.get"" IL_0007: stobj ""B"" IL_000c: ldarg.2 IL_000d: ldarg.0 IL_000e: call ""readonly int C.Z.get"" IL_0013: stind.i4 IL_0014: ret }"); } [Fact] public void Deconstruct_PropertyCollision() { var source = @"using System; record struct B(int X, int Y) { public int X => 3; static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "32"); verifier.VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_01() { var source = @" record struct B(int X, int Y) { public int X() => 3; static void M(B b) { switch (b) { case B(int x, int y): break; } } static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'B' already contains a definition for 'X' // public int X() => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("B", "X").WithLocation(4, 16) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_FieldCollision() { var source = @" using System; record struct C(int X) { int X = 0; static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(0)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 21), // (6,9): warning CS0414: The field 'C.X' is assigned but its value is never used // int X = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "X").WithArguments("C.X").WithLocation(6, 9)); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty() { var source = @" record struct C { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Conversion_02() { var source = @" #nullable enable using System; record struct C(string? X, string Y) { public string X { get; init; } = null!; public string? Y { get; init; } = string.Empty; static void M(C c) { switch (c) { case C(var x, string y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(""a"", ""b"")); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,25): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 25), // (5,35): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 35) ); Assert.Equal( "void C.Deconstruct(out System.String? X, out System.String Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty_WithParameterList() { var source = @" record struct C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); AssertEx.Equal(new[] { "C..ctor()", "void C.M(C c)", "void C.Main()", "System.String C.ToString()", "System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object obj)", "System.Boolean C.Equals(C other)" }, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings()); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_01() { var source = @"using System; record struct C(int I) { public void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C(42)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_UserDefined() { var source = @"using System; record struct B(int X, int Y) { public void Deconstruct(out int X, out int Y) { X = this.X + 1; Y = this.Y + 2; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(0, 0)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_02() { var source = @"using System; record struct B(int X) { public int Deconstruct(out int a) => throw null; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS8874: Record member 'B.Deconstruct(out int)' must return 'void'. // public int Deconstruct(out int a) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Deconstruct").WithArguments("B.Deconstruct(out int)", "void").WithLocation(5, 16), // (11,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'B', with 1 out parameters and a void return type. // case B(int x): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int x)").WithArguments("B", "1").WithLocation(11, 19)); Assert.Equal("System.Int32 B.Deconstruct(out System.Int32 a)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void Deconstruct_UserDefined_Accessibility_07(string accessibility) { var source = $@" record struct A(int X) {{ { accessibility } void Deconstruct(out int a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,11): error CS8873: Record member 'A.Deconstruct(out int)' must be public. // void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void Deconstruct_UserDefined_Static_08() { var source = @" record struct A(int X) { public static void Deconstruct(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS8877: Record member 'A.Deconstruct(out int)' may not be static. // public static void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 24) ); } [Fact] public void OutVarInPositionalParameterDefaultValue() { var source = @" record struct A(int X = A.M(out int a) + a) { public static int M(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,25): error CS1736: Default parameter value for 'X' must be a compile-time constant // record struct A(int X = A.M(out int a) + a) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "A.M(out int a) + a").WithArguments("X").WithLocation(2, 25) ); } [Fact] public void FieldConsideredUnassignedIfInitializationViaProperty() { var source = @" record struct Pos(int X) { private int x; public int X { get { return x; } set { x = value; } } = X; } record struct Pos2(int X) { private int x = X; // value isn't validated by setter public int X { get { return x; } set { x = value; } } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0171: Field 'Pos.x' must be fully assigned before control is returned to the caller // record struct Pos(int X) Diagnostic(ErrorCode.ERR_UnassignedThis, "Pos").WithArguments("Pos.x").WithLocation(2, 15), // (5,16): error CS8050: Only auto-implemented properties can have initializers. // public int X { get { return x; } set { x = value; } } = X; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "X").WithArguments("Pos.X").WithLocation(5, 16) ); } [Fact] public void IEquatableT_01() { var source = @"record struct A<T>; class Program { static void F<T>(System.IEquatable<T> t) { } static void M<T>() { F(new A<T>()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( ); } [Fact] public void IEquatableT_02() { var source = @"using System; record struct A; record struct B<T>; class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "TrueTrue").VerifyDiagnostics(); } [Fact] public void IEquatableT_02_ImplicitImplementation() { var source = @"using System; record struct A { public bool Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { public bool Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics( // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17), // (12,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B<T> other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(12, 17) ); } [Fact] public void IEquatableT_02_ExplicitImplementation() { var source = @"using System; record struct A { bool IEquatable<A>.Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { bool IEquatable<B<T>>.Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics(); } [Fact] public void IEquatableT_03() { var source = @" record struct A<T> : System.IEquatable<A<T>>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_MissingIEquatable() { var source = @" record struct A<T>; "; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_IEquatable_T); comp.VerifyEmitDiagnostics( // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void RecordEquals_01() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); record struct B { public bool Equals(B other) { System.Console.WriteLine(""B.Equals(B)""); return false; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 17) ); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False "); } [Fact] public void RecordEquals_01_NoInParameters() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(in a2)); record struct B; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,39): error CS1615: Argument 1 may not be passed with the 'in' keyword // System.Console.WriteLine(a1.Equals(in a2)); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "a2").WithArguments("1", "in").WithLocation(4, 39) ); } [Theory] [InlineData("protected")] [InlineData("private protected")] [InlineData("internal protected")] public void RecordEquals_10(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,29): error CS0666: 'A.Equals(A)': new protected member declared in struct // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): error CS8873: Record member 'A.Equals(A)' must be public. // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // internal protected bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void RecordEquals_11(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,11): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void RecordEquals_12() { var source = @" A a1 = new A(); A a2 = new A(); System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); record struct A { public bool Equals(B other) => throw null; } class B { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); var objectEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordObjEquals>().Single(); Assert.Equal("System.Boolean A.Equals(System.Object obj)", objectEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, objectEquals.DeclaredAccessibility); Assert.False(objectEquals.IsAbstract); Assert.False(objectEquals.IsVirtual); Assert.True(objectEquals.IsOverride); Assert.False(objectEquals.IsSealed); Assert.True(objectEquals.IsImplicitlyDeclared); MethodSymbol gethashCode = comp.GetMembers("A." + WellKnownMemberNames.ObjectGetHashCode).OfType<SynthesizedRecordGetHashCode>().Single(); Assert.Equal("System.Int32 A.GetHashCode()", gethashCode.ToTestDisplayString()); Assert.Equal(Accessibility.Public, gethashCode.DeclaredAccessibility); Assert.False(gethashCode.IsStatic); Assert.False(gethashCode.IsAbstract); Assert.False(gethashCode.IsVirtual); Assert.True(gethashCode.IsOverride); Assert.False(gethashCode.IsSealed); Assert.True(gethashCode.IsImplicitlyDeclared); } [Fact] public void RecordEquals_13() { var source = @" record struct A { public int Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,16): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public int Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 16), // (4,16): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public int Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 16) ); } [Fact] public void RecordEquals_14() { var source = @" record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (4,12): error CS0518: Predefined type 'System.Boolean' is not defined or imported // public bool Equals(A other) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 12), // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17) ); } [Fact] public void RecordEquals_19() { var source = @" record struct A { public static bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void RecordEquals_RecordEqualsInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool Equals(A x) => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) ); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A other)", recordEquals.ToTestDisplayString()); } [Fact] public void RecordEquals_FourFields() { var source = @" A a1 = new A(1, ""hello""); System.Console.Write(a1.Equals(a1)); System.Console.Write(a1.Equals((object)a1)); System.Console.Write("" - ""); A a2 = new A(1, ""hello"") { fieldI = 100 }; System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); System.Console.Write(a2.Equals(a1)); System.Console.Write(a2.Equals((object)a1)); System.Console.Write("" - ""); A a3 = new A(1, ""world""); System.Console.Write(a1.Equals(a3)); System.Console.Write(a1.Equals((object)a3)); System.Console.Write(a3.Equals(a1)); System.Console.Write(a3.Equals((object)a1)); record struct A(int I, string S) { public int fieldI = 42; public string fieldS = ""hello""; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue - FalseFalseFalseFalse - FalseFalseFalseFalse"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 97 (0x61) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int A.<I>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_005f IL_0018: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""string A.<S>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""string A.<S>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_002e: brfalse.s IL_005f IL_0030: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0035: ldarg.0 IL_0036: ldfld ""int A.fieldI"" IL_003b: ldarg.1 IL_003c: ldfld ""int A.fieldI"" IL_0041: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0046: brfalse.s IL_005f IL_0048: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_004d: ldarg.0 IL_004e: ldfld ""string A.fieldS"" IL_0053: ldarg.1 IL_0054: ldfld ""string A.fieldS"" IL_0059: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_005e: ret IL_005f: ldc.i4.0 IL_0060: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 86 (0x56) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""string A.<S>k__BackingField"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0026: add IL_0027: ldc.i4 0xa5555529 IL_002c: mul IL_002d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0032: ldarg.0 IL_0033: ldfld ""int A.fieldI"" IL_0038: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_003d: add IL_003e: ldc.i4 0xa5555529 IL_0043: mul IL_0044: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_0049: ldarg.0 IL_004a: ldfld ""string A.fieldS"" IL_004f: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0054: add IL_0055: ret }"); } [Fact] public void RecordEquals_StaticField() { var source = @" record struct A { public static int field = 42; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void ObjectEquals_06() { var source = @" record struct A { public static new bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,28): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public static new bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(4, 28) ); } [Fact] public void ObjectEquals_UserDefined() { var source = @" record struct A { public override bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,26): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public override bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(4, 26) ); } [Fact] public void GetHashCode_UserDefined() { var source = @" System.Console.Write(new A().GetHashCode()); record struct A { public override int GetHashCode() => 42; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void GetHashCode_GetHashCodeInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public virtual int GetHashCode() => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (2,22): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public record struct A; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "A").WithArguments("A.GetHashCode()").WithLocation(2, 22) ); } [Fact] public void GetHashCode_MissingEqualityComparer_EmptyRecord() { var src = @" public record struct A; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics(); } [Fact] public void GetHashCode_MissingEqualityComparer_NonEmptyRecord() { var src = @" public record struct A(int I); "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1) ); } [Fact] public void GetHashCodeIsDefinedButEqualsIsNot() { var src = @" public record struct C { public object Data; public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void EqualsIsDefinedButGetHashCodeIsNot() { var src = @" public record struct C { public object Data; public bool Equals(C c) { return false; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) { return false; } Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(5, 17)); } [Fact] public void EqualityOperators_01() { var source = @" record struct A(int X) { public bool Equals(ref A other) => throw null; static void Main() { Test(default, default); Test(default, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); var a = new A(11); Test(a, a); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False True True False False True True False False False False True True True True False False ").VerifyDiagnostics(); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A left, A right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A left, A right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: ldarg.1 IL_0003: call ""bool A.Equals(A)"" IL_0008: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_03() { var source = @" record struct A { public static bool operator==(A r1, A r2) => throw null; public static bool operator==(A r1, string r2) => throw null; public static bool operator!=(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool operator==(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "==").WithArguments("op_Equality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_04() { var source = @" record struct A { public static bool operator!=(A r1, A r2) => throw null; public static bool operator!=(string r1, A r2) => throw null; public static bool operator==(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool operator!=(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "!=").WithArguments("op_Inequality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_05() { var source = @" record struct A { public static bool op_Equality(A r1, A r2) => throw null; public static bool op_Equality(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool op_Equality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Equality").WithArguments("op_Equality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_06() { var source = @" record struct A { public static bool op_Inequality(A r1, A r2) => throw null; public static bool op_Inequality(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool op_Inequality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Inequality").WithArguments("op_Inequality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_07() { var source = @" record struct A { public static bool Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A other) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Theory] [CombinatorialData] public void EqualityOperators_09(bool useImageReference) { var source1 = @" public record struct A(int X); "; var comp1 = CreateCompilation(source1); var source2 = @" class Program { static void Main() { Test(default, default); Test(default, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; CompileAndVerify(source2, references: new[] { useImageReference ? comp1.EmitToImageReference() : comp1.ToMetadataReference() }, expectedOutput: @" True True False False True True False False True True False False False False True True ").VerifyDiagnostics(); } [Fact] public void GetSimpleNonTypeMembers_DirectApiCheck() { var src = @" public record struct RecordB(); "; var comp = CreateCompilation(src); var b = comp.GlobalNamespace.GetTypeMember("RecordB"); AssertEx.SetEqual(new[] { "System.Boolean RecordB.op_Equality(RecordB left, RecordB right)" }, b.GetSimpleNonTypeMembers("op_Equality").ToTestDisplayStrings()); } [Fact] public void ToString_NestedRecord() { var src = @" var c1 = new Outer.C1(42); System.Console.Write(c1.ToString()); public class Outer { public record struct C1(int I1); } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }"); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }"); compRelease.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_Empty() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: call ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilder() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Text_StringBuilder); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record struct C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 15) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderCtor() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__ctor); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderAppendString() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString() { var src = @" record struct C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_RecordWithIndexer() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record struct C1(int I1) { private int field = 44; public int this[int i] => 0; public int PropertyWithoutGetter { set { } } public int P2 { get => 43; } public event System.Action a = null; private int field1 = 100; internal int field2 = 100; private int Property1 { get; set; } = 100; internal int Property2 { get; set; } = 100; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43 }"); comp.VerifyEmitDiagnostics( // (7,17): warning CS0414: The field 'C1.field' is assigned but its value is never used // private int field = 44; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C1.field").WithLocation(7, 17), // (11,32): warning CS0414: The field 'C1.a' is assigned but its value is never used // public event System.Action a = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("C1.a").WithLocation(11, 32), // (13,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used // private int field1 = 100; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1").WithArguments("C1.field1").WithLocation(13, 17) ); } [Fact] public void ToString_PrivateGetter() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public int P1 { private get => 43; set => throw null; } } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }"); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_OneField_ValueType() { var src = @" var c1 = new C1() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1 { public int field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldflda ""int C1.field"" IL_0013: constrained. ""int"" IL_0019: callvirt ""string object.ToString()"" IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0023: pop IL_0024: ldc.i4.1 IL_0025: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ConstrainedValueType() { var src = @" var c1 = new C1<int>() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1<T> where T : struct { public T field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 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] public void ToString_TopLevelRecord_OneField_ReferenceType() { var src = @" var c1 = new C1() { field = ""hello"" }; System.Console.Write(c1.ToString()); record struct C1 { public string field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldfld ""string C1.field"" IL_0013: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0018: pop IL_0019: ldc.i4.1 IL_001a: ret } "); } [Fact] public void ToString_TopLevelRecord_TwoFields_ReferenceType() { var src = @" var c1 = new C1(42) { field1 = ""hi"", field2 = null }; System.Console.Write(c1.ToString()); record struct C1(int I) { public string field1 = null; public string field2 = null; private string field3 = null; internal string field4 = null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,20): warning CS0414: The field 'C1.field3' is assigned but its value is never used // private string field3 = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field3").WithArguments("C1.field3").WithLocation(10, 20) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42, field1 = hi, field2 = }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 91 (0x5b) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""readonly int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldarg.1 IL_0028: ldstr "", field1 = "" IL_002d: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0032: pop IL_0033: ldarg.1 IL_0034: ldarg.0 IL_0035: ldfld ""string C1.field1"" IL_003a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_003f: pop IL_0040: ldarg.1 IL_0041: ldstr "", field2 = "" IL_0046: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_004b: pop IL_004c: ldarg.1 IL_004d: ldarg.0 IL_004e: ldfld ""string C1.field2"" IL_0053: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0058: pop IL_0059: ldc.i4.1 IL_005a: ret } "); } [Fact] public void ToString_TopLevelRecord_Readonly() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); readonly record struct C1(int I); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 41 (0x29) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldc.i4.1 IL_0028: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: call ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public override string ToString() => ""RAN""; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString()); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_New() { var src = @" record struct C1 { public new string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS8869: 'C1.ToString()' does not override expected method from 'object'. // public new string ToString() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "ToString").WithArguments("C1.ToString()").WithLocation(4, 23) ); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_Sealed() { var src = @" record struct C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,35): error CS0106: The modifier 'sealed' is not valid for this item // public sealed override string ToString() => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("sealed").WithLocation(4, 35) ); } [Fact] public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder() { var src = @" #nullable enable record struct C1 { private bool PrintMembers(System.Text.StringBuilder? builder) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_ErrorReturnType() { var src = @" record struct C1 { private Error PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,13): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // private Error PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 13) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongReturnType() { var src = @" record struct C1 { private int PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,17): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'. // private int PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 17) ); } [Fact] public void ToString_UserDefinedPrintMembers() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1 { private bool PrintMembers(System.Text.StringBuilder builder) { builder.Append(""RAN""); return true; } public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { RAN } - RAN"); } [Fact] public void ToString_CallingSynthesizedPrintMembers() { var src = @" var c1 = new C1(1, 2, 3); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1(int I, int I2, int I3) { public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { I = 1, I2 = 2, I3 = 3 } - I = 1, I2 = 2, I3 = 3"); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility() { var src = @" var c = new C1(); System.Console.Write(c.ToString()); record struct C1 { internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (7,19): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private. // internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(7, 19) ); } [Fact] public void ToString_UserDefinedPrintMembers_Static() { var src = @" record struct C1 { static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8877: Record member 'C1.PrintMembers(StringBuilder)' may not be static. // static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void AmbigCtor_WithPropertyInitializer() { // Scenario causes ambiguous ctor for record class, but not record struct var src = @" record struct R(R X) { public R X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,14): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // public R X { get; init; } = X; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(4, 14) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var parameterSyntax = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); var parameter = model.GetDeclaredSymbol(parameterSyntax)!; Assert.Equal("R X", parameter.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, parameter.Kind); Assert.Equal("R..ctor(R X)", parameter.ContainingSymbol.ToTestDisplayString()); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); var initializer = model.GetSymbolInfo(initializerSyntax.Value).Symbol!; Assert.Equal("R X", initializer.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, initializer.Kind); Assert.Equal("R..ctor(R X)", initializer.ContainingSymbol.ToTestDisplayString()); var src2 = @" record struct R(R X); "; var comp2 = CreateCompilation(src2); comp2.VerifyEmitDiagnostics( // (2,19): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // record struct R(R X); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(2, 19) ); } [Fact] public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer() { var src = @" record struct R(int I) { public int I { get; init; } = M(out int i); static int M(out int i) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 21) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var outVarSyntax = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Single(); var outVar = model.GetDeclaredSymbol(outVarSyntax)!; Assert.Equal("System.Int32 i", outVar.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, outVar.Kind); Assert.Equal("System.Int32 R.<I>k__BackingField", outVar.ContainingSymbol.ToTestDisplayString()); } [Fact] public void AnalyzerActions_01() { // Test RegisterSyntaxNodeAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } interface I1 {} class Attr1 : System.Attribute {} "; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCountRecordStructDeclarationA); Assert.Equal(1, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCountConstructorDeclaration); Assert.Equal(1, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount0; public int FireCountRecordStructDeclarationA; public int FireCountRecordStructDeclarationACtor; public int FireCount3; public int FireCountSimpleBaseTypeI1onA; public int FireCount5; public int FireCountParameterListAPrimaryCtor; public int FireCount7; public int FireCountConstructorDeclaration; public int FireCountStringParameterList; public int FireCountThisConstructorInitializer; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); } protected void Handle1(SyntaxNodeAnalysisContext context) { var literal = (LiteralExpressionSyntax)context.Node; switch (literal.ToString()) { case "0": Interlocked.Increment(ref FireCount0); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "3": Interlocked.Increment(ref FireCount7); Assert.Equal("System.Int32 A.M()", context.ContainingSymbol.ToTestDisplayString()); break; case "4": Interlocked.Increment(ref FireCount12); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(literal.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle2(SyntaxNodeAnalysisContext context) { var equalsValue = (EqualsValueClauseSyntax)context.Node; switch (equalsValue.ToString()) { case "= 0": Interlocked.Increment(ref FireCount3); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(equalsValue.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle3(SyntaxNodeAnalysisContext context) { var initializer = (ConstructorInitializerSyntax)context.Node; switch (initializer.ToString()) { case ": this(4)": Interlocked.Increment(ref FireCountThisConstructorInitializer); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(initializer.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle4(SyntaxNodeAnalysisContext context) { Interlocked.Increment(ref FireCountConstructorDeclaration); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); } protected void Fail(SyntaxNodeAnalysisContext context) { Assert.True(false); } protected void Handle6(SyntaxNodeAnalysisContext context) { var record = (RecordDeclarationSyntax)context.Node; Assert.Equal(SyntaxKind.RecordStructDeclaration, record.Kind()); switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCountRecordStructDeclarationA); break; case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCountRecordStructDeclarationACtor); break; default: Assert.True(false); break; } Assert.Same(record.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle7(SyntaxNodeAnalysisContext context) { var identifier = (IdentifierNameSyntax)context.Node; switch (identifier.Identifier.ValueText) { case "Attr1": Interlocked.Increment(ref FireCount5); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; } } protected void Handle8(SyntaxNodeAnalysisContext context) { var baseType = (SimpleBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "I1": switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCountSimpleBaseTypeI1onA); break; default: Assert.True(false); break; } break; case "System.Attribute": break; default: Assert.True(false); break; } } protected void Handle9(SyntaxNodeAnalysisContext context) { var parameterList = (ParameterListSyntax)context.Node; switch (parameterList.ToString()) { case "([Attr1]int X = 0)": Interlocked.Increment(ref FireCountParameterListAPrimaryCtor); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "(string S)": Interlocked.Increment(ref FireCountStringParameterList); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; case "()": break; default: Assert.True(false); break; } } protected void Handle10(SyntaxNodeAnalysisContext context) { var argumentList = (ArgumentListSyntax)context.Node; switch (argumentList.ToString()) { case "(4)": Interlocked.Increment(ref FireCount11); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { // Test RegisterSymbolAction var text1 = @" record struct A(int X = 0) {} record struct C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); context.RegisterSymbolAction(Handle, SymbolKind.Property); context.RegisterSymbolAction(Handle, SymbolKind.Parameter); context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "System.Int32 A.X { get; set; }": Interlocked.Increment(ref FireCount2); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount6); break; case "C": Interlocked.Increment(ref FireCount7); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { // Test RegisterSymbolStartAction var text1 = @" readonly record struct A(int X = 0) {} readonly record struct C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(0, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle1, SymbolKind.Property); context.RegisterSymbolStartAction(Handle1, SymbolKind.Parameter); context.RegisterSymbolStartAction(Handle1, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle2); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle3); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); context.RegisterSymbolEndAction(Handle4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount9); Assert.Equal(0, FireCount1); Assert.Equal(0, FireCount2); Assert.Equal(0, FireCount6); Assert.Equal(0, FireCount7); context.RegisterSymbolEndAction(Handle5); break; case "C": Interlocked.Increment(ref FireCount10); Assert.Equal(0, FireCount4); Assert.Equal(0, FireCount8); context.RegisterSymbolEndAction(Handle6); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { Assert.Equal("A..ctor([System.Int32 X = 0])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("System.Int32 A.X { get; init; }", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("C..ctor([System.Int32 Z = 4])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal("A", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); Assert.Equal(1, FireCount1); Assert.Equal(1, FireCount2); Assert.Equal(1, FireCount6); Assert.Equal(1, FireCount7); } private void Handle6(SymbolAnalysisContext context) { Assert.Equal("C", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); Assert.Equal(1, FireCount4); Assert.Equal(1, FireCount8); } } [Fact] public void AnalyzerActions_04() { // Test RegisterOperationAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} interface I1 {} "; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount14); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount6; public int FireCount7; public int FireCount14; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(HandleConstructorBody, OperationKind.ConstructorBody); context.RegisterOperationAction(HandleInvocation, OperationKind.Invocation); context.RegisterOperationAction(HandleLiteral, OperationKind.Literal); context.RegisterOperationAction(HandleParameterInitializer, OperationKind.ParameterInitializer); context.RegisterOperationAction(Fail, OperationKind.PropertyInitializer); context.RegisterOperationAction(Fail, OperationKind.FieldInitializer); } protected void HandleConstructorBody(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @""); break; default: Assert.True(false); break; } } protected void HandleInvocation(OperationAnalysisContext context) { Assert.True(false); } protected void HandleLiteral(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "100": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); break; case "0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); break; default: Assert.True(false); break; } } protected void HandleParameterInitializer(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "= 0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount14); break; default: Assert.True(false); break; } } protected void Fail(OperationAnalysisContext context) { Assert.True(false); } } [Fact] public void AnalyzerActions_05() { // Test RegisterOperationBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} interface I1 {} "; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { // Test RegisterCodeBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 { int M() => 3; } interface I1 {} "; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_08() { // Test RegisterCodeBlockStartAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } interface I1 {} "; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(1, analyzer.FireCount500); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationA); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(0, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(0, analyzer.FireCountConstructorDeclaration); Assert.Equal(0, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount4000); Assert.Equal(1, analyzer.FireCount5000); } private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer { public int FireCount100; public int FireCount400; public int FireCount500; public int FireCount1000; public int FireCount4000; public int FireCount5000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount100); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount400); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount500); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); context.RegisterCodeBlockEndAction(Handle11); } private void Handle11(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1000); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4000); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount5000); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_09() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Property); context.RegisterSymbolAction(Handle3, SymbolKind.Parameter); } private void Handle1(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount5); break; case "System.Int32 B.Y { get; init; }": Interlocked.Increment(ref FireCount6); break; default: Assert.True(false); break; } } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount7); break; case "[System.Int32 Y = 1]": Interlocked.Increment(ref FireCount8); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount9); break; default: Assert.True(false); break; } } } [Fact] public void WithExprOnStruct_LangVersion() { var src = @" var b = new B() { X = 1 }; var b2 = b.M(); System.Console.Write(b2.X); System.Console.Write("" ""); System.Console.Write(b.X); public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42 }; }/*</bind>*/ }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,16): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater. // return this with { X = 42 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "this with { X = 42 }").WithArguments("with on structs", "10.0").WithLocation(13, 16) ); comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 1"); verifier.VerifyIL("B.M", @" { // Code size 18 (0x12) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: ldobj ""B"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: ldc.i4.s 42 IL_000b: call ""void B.X.set"" IL_0010: ldloc.0 IL_0011: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("B", type.Type.ToTestDisplayString()); var operation = model.GetOperation(with); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: B) (Syntax: 'this with { X = 42 }') Operand: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: B) (Syntax: '{ X = 42 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_DuplicateInitialization() { var src = @" public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42, X = 43 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (8,36): error CS1912: Duplicate initialization of member 'X' // return this with { X = 42, X = 43 }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'X = 43') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 43) (Syntax: '43') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NestedInitializer() { var src = @" public struct C { public int Y { get; set; } } public struct B { public C X { get; set; } public B M() /*<bind>*/{ return this with { X = { Y = 1 } }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (12,32): error CS1525: Invalid expression term '{' // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(12, 32), // (12,32): error CS1513: } expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(12, 32), // (12,32): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(12, 32), // (12,34): error CS0103: The name 'Y' does not exist in the current context // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y").WithLocation(12, 34), // (12,34): warning CS0162: Unreachable code detected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.WRN_UnreachableCode, "Y").WithLocation(12, 34), // (12,40): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(12, 40), // (12,43): error CS1597: Semicolon after method or accessor block is not valid // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(12, 43), // (14,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(14, 1) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'X = ') Left: IPropertyReferenceOperation: C B.X { get; set; } (OperationKind.PropertyReference, Type: C) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Return) Block[B3] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Y = 1 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Y = 1') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Y') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NonAssignmentExpression() { var src = @" public struct B { public int X { get; set; } public B M(int i, int j) /*<bind>*/{ return this with { i, j++, M2(), X = 2}; }/*</bind>*/ static int M2() => 0; }"; var expectedDiagnostics = new[] { // (8,28): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(8, 28), // (8,31): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(8, 31), // (8,36): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 B.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void ObjectCreationInitializer_ControlFlow_WithCoalescingExpressionForValue() { var src = @" public struct B { public string X; public void M(string hello) /*<bind>*/{ var x = new B() { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [B x] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Value: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B) (Syntax: 'new B() { X ... ty(hello) }') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics); } [Fact] public void WithExprOnStruct_ControlFlow_WithCoalescingExpressionForValue() { var src = @" var b = new B() { X = string.Empty }; var b2 = b.M(""hello""); System.Console.Write(b2.X); public struct B { public string X; public B M(string hello) /*<bind>*/{ return Identity(this) with { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(this)') Value: IInvocationOperation ( B B.Identity<B>(B t)) (OperationKind.Invocation, Type: B) (Syntax: 'Identity(this)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (0) Next (Return) Block[B7] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_OnParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public struct B { public int X { get; set; } public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnThis() { var src = @" record struct C { public int X { get; set; } C(string ignored) { _ = this with { X = 42 }; // 1 this = default; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0188: The 'this' object cannot be used before all of its fields have been assigned // _ = this with { X = 42 }; // 1 Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this").WithLocation(8, 13) ); } [Fact] public void WithExprOnStruct_OnTStructParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public interface I { int X { get; set; } } public struct B : I { public int X { get; set; } public static T M<T>(T b) where T : struct, I { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M<T>(T)", @" { // Code size 19 (0x13) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: constrained. ""T"" IL_000c: callvirt ""void I.X.set"" IL_0011: ldloc.0 IL_0012: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("T", type.Type.ToTestDisplayString()); } [Fact] public void WithExprOnStruct_OnRecordStructParameter() { var src = @" var b = new B(1); var b2 = B.M(b); System.Console.Write(b2.X); public record struct B(int X) { public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnRecordStructParameter_Readonly() { var src = @" var b = new B(1, 2); var b2 = B.M(b); System.Console.Write(b2.X); System.Console.Write(b2.Y); public readonly record struct B(int X, int Y) { public static B M(B b) { return b with { X = 42, Y = 43 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("B.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.init"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: call ""void B.Y.init"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple() { var src = @" class C { static void Main() { var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); } static (int, int) M((int, int) b) { return b with { Item1 = 42, Item2 = 43 }; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_WithNames() { var src = @" var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); static (int, int) M((int X, int Y) b) { return b with { X = 42, Y = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int>)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_LongTuple() { var src = @" var b = (1, 2, 3, 4, 5, 6, 7, 8); var b2 = M(b); System.Console.Write(b2.Item7); System.Console.Write(b2.Item8); static (int, int, int, int, int, int, int, int) M((int, int, int, int, int, int, int, int) b) { return b with { Item7 = 42, Item8 = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>)", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item7"" IL_000b: ldloca.s V_0 IL_000d: ldflda ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest"" IL_0012: ldc.i4.s 43 IL_0014: stfld ""int System.ValueTuple<int>.Item1"" IL_0019: ldloc.0 IL_001a: ret }"); } [Fact] public void WithExprOnStruct_OnReadonlyField() { var src = @" var b = new B { X = 1 }; // 1 public struct B { public readonly int X; public B M() { return this with { X = 42 }; // 2 } public static B M2(B b) { return b with { X = 42 }; // 3 } public B(int i) { this = default; _ = this with { X = 42 }; // 4 } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // var b = new B { X = 1 }; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(2, 17), // (9,28): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return this with { X = 42 }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(9, 28), // (13,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return b with { X = 42 }; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(13, 25), // (18,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = this with { X = 42 }; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(18, 25) ); } [Fact] public void WithExprOnStruct_OnEnum() { var src = @" public enum E { } class C { static E M(E e) { return e with { }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void WithExprOnStruct_OnPointer() { var src = @" unsafe class C { static int* M(int* i) { return i with { }; } }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (6,16): error CS8858: The receiver type 'int*' is not a valid record type and is not a struct type. // return i with { }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("int*").WithLocation(6, 16) ); } [Fact] public void WithExprOnStruct_OnInterface() { var src = @" public interface I { int X { get; set; } } class C { static I M(I i) { return i with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,16): error CS8858: The receiver type 'I' is not a valid record type and is not a value type. // return i with { X = 42 }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("I").WithLocation(10, 16) ); } [Fact] public void WithExprOnStruct_OnRefStruct() { // Similar to test RefLikeObjInitializers but with `with` expressions var text = @" using System; class Program { static S2 Test1() { S1 outer = default; S1 inner = stackalloc int[1]; // error return new S2() with { Field1 = outer, Field2 = inner }; } static S2 Test2() { S1 outer = default; S1 inner = stackalloc int[1]; S2 result; // error result = new S2() with { Field1 = inner, Field2 = outer }; return result; } static S2 Test3() { S1 outer = default; S1 inner = stackalloc int[1]; return new S2() with { Field1 = outer, Field2 = outer }; } public ref struct S1 { public static implicit operator S1(Span<int> o) => default; } public ref struct S2 { public S1 Field1; public S1 Field2; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (12,48): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return new S2() with { Field1 = outer, Field2 = inner }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field2 = inner").WithArguments("inner").WithLocation(12, 48), // (23,34): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // result = new S2() with { Field1 = inner, Field2 = outer }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field1 = inner").WithArguments("inner").WithLocation(23, 34) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap() { // Similar to test LocalWithNoInitializerEscape but wrapping method is used as receiver for `with` expression var text = @" using System; class Program { static void Main() { S1 sp; Span<int> local = stackalloc int[1]; sp = MayWrap(ref local) with { }; // 1, 2 } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (9,26): error CS8352: Cannot use local 'local' in this context because it may expose referenced variables outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "local").WithArguments("local").WithLocation(9, 26), // (9,14): error CS8347: Cannot use a result of 'Program.MayWrap(ref Span<int>)' in this context because it may expose variables referenced by parameter 'arg' outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeCall, "MayWrap(ref local)").WithArguments("Program.MayWrap(ref System.Span<int>)", "arg").WithLocation(9, 14) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap_02() { var text = @" using System; class Program { static void Main() { Span<int> local = stackalloc int[1]; S1 sp = MayWrap(ref local) with { }; } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_01() { var src = @" #nullable enable record struct B(int X) { static void M(B b) { string? s = null; _ = b with { X = M(out s) }; s.ToString(); } static int M(out string s) { s = ""a""; return 42; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_02() { var src = @" #nullable enable record struct B(string X) { static void M(B b, string? s) { b.X.ToString(); _ = b with { X = s }; // 1 b.X.ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): warning CS8601: Possible null reference assignment. // _ = b with { X = s }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(8, 26)); } [Fact] public void WithExpr_NullableAnalysis_03() { var src = @" #nullable enable record struct B(string? X) { static void M1(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 1 _ = b with { X = s }; if (flag) { b.X.ToString(); } // 2 } static void M2(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 3 b = b with { X = s }; if (flag) { b.X.ToString(); } } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(7, 21), // (9,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(9, 21), // (14,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(14, 21)); } [Fact, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")] public void WithExpr_NullableAnalysis_05() { var src = @" #nullable enable record struct B(string? X, string? Y) { static void M1(bool flag) { B b = new B(""hello"", null); if (flag) { b.X.ToString(); // shouldn't warn b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); // shouldn't warn b.Y.ToString(); } }"; // records should propagate the nullability of the // constructor arguments to the corresponding properties. // https://github.com/dotnet/roslyn/issues/44763 var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(11, 13), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_06() { var src = @" #nullable enable struct B { public string? X { get; init; } public string? Y { get; init; } static void M1(bool flag) { B b = new B { X = ""hello"", Y = null }; if (flag) { b.X.ToString(); b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); b.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(14, 13) ); } [Fact] public void WithExprAssignToRef1() { var src = @" using System; record struct C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X => ref _a[0]; public static void Main() { var c = new C(0) { X = 5 }; Console.WriteLine(c.X); c = c with { X = 1 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 59 (0x3b) .maxstack 2 .locals init (C V_0, //c C V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.0 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_1 IL_000a: call ""ref int C.X.get"" IL_000f: ldc.i4.5 IL_0010: stind.i4 IL_0011: ldloc.1 IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: call ""ref int C.X.get"" IL_001a: ldind.i4 IL_001b: call ""void System.Console.WriteLine(int)"" IL_0020: ldloc.0 IL_0021: stloc.1 IL_0022: ldloca.s V_1 IL_0024: call ""ref int C.X.get"" IL_0029: ldc.i4.1 IL_002a: stind.i4 IL_002b: ldloc.1 IL_002c: stloc.0 IL_002d: ldloca.s V_0 IL_002f: call ""ref int C.X.get"" IL_0034: ldind.i4 IL_0035: call ""void System.Console.WriteLine(int)"" IL_003a: ret }"); } [Fact] public void WithExpressionSameLHS() { var comp = CreateCompilation(@" record struct C(int X) { public static void Main() { var c = new C(0); c = c with { X = 1, X = 2}; } }"); comp.VerifyDiagnostics( // (7,29): error CS1912: Duplicate initialization of member 'X' // c = c with { X = 1, X = 2}; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(7, 29) ); } [Fact] public void WithExpr_AnonymousType_ChangeAllProperties() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { A = Identity(30), B = Identity(40) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,17): error CS8773: Feature 'with on anonymous types' is not available in C# 9.0. Please use language version 10.0 or greater. // var b = Identity(a) with { A = Identity(30), B = Identity(40) }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Identity(a) with { A = Identity(30), B = Identity(40) }").WithArguments("with on anonymous types", "10.0").WithLocation(9, 17) ); comp = CreateCompilation(src, parseOptions: TestOptions.Regular10); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(30) Identity(40) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 30 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: ldc.i4.s 40 IL_0018: call ""int C.Identity<int>(int)"" IL_001d: stloc.0 IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeAllProperties_ReverseOrder() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = Identity(40), A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(40) Identity(30) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 40 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: stloc.0 IL_0017: ldc.i4.s 30 IL_0019: call ""int C.Identity<int>(int)"" IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeNoProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = M2(a) with { }; System.Console.Write(b); }/*</bind>*/ static T M2<T>(T t) { System.Console.Write(""M2 ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "M2 { A = 10, B = 20 }"); verifier.VerifyIL("C.M", @" { // Code size 38 (0x26) .maxstack 2 .locals init (<>f__AnonymousType0<int, int> V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.M2<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0015: ldloc.0 IL_0016: callvirt ""int <>f__AnonymousType0<int, int>.B.get"" IL_001b: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0020: call ""void System.Console.Write(object)"" IL_0025: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.M2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a) with { }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = a with { B = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: ldc.i4.s 30 IL_000b: call ""int C.Identity<int>(int)"" IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var withExpr = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var operation = model.GetOperation(withExpr); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '{ B = Identity(30) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'B = Identity(30)') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'B') Right: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithMethodCallForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: ldc.i4.s 30 IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = (Identity(a) ?? Identity2(a)) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; static T Identity2<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} {R5} } .locals {R3} { CaptureIds: [4] [5] .locals {R4} { CaptureIds: [2] .locals {R5} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(a)') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Leaving: {R5} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B5] Leaving: {R5} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B6] Leaving: {R4} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '(Identity(a ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForValue() { var src = @" C.M(""hello"", ""world""); public class C { public static void M(string hello, string world) /*<bind>*/{ var x = new { A = hello, B = string.Empty }; var y = x with { B = Identity(null) ?? Identity2(world) }; System.Console.Write(y); }/*</bind>*/ static string Identity(string t) => t; static string Identity2(string t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = hello, B = world }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.String A, System.String B> x] [<anonymous type: System.String A, System.String B> y] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'hello') Value: IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'string.Empty') Value: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'new { A = h ... ing.Empty }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'A = hello') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'hello') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'B = string.Empty') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'string.Empty') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [5] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x') Next (Regular) Block[B3] Entering: {R5} .locals {R5} { CaptureIds: [4] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IInvocationOperation (System.String C.Identity(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(null)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(null)') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Leaving: {R5} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Next (Regular) Block[B6] Leaving: {R5} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(world)') Value: IInvocationOperation (System.String C.Identity2(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity2(world)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'world') IParameterReferenceOperation: world (OperationKind.ParameterReference, Type: System.String) (Syntax: 'world') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Value: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B7] Leaving: {R4} } Block[B7] - Block Predecessors: [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x with { B ... y2(world) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B8] Leaving: {R3} } Block[B8] - Block Predecessors: [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(y);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ErrorMember() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { Error = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0117: '<anonymous type: int A>' does not contain a definition for 'Error' // var b = a with { Error = Identity(20) }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("<anonymous type: int A>", "Error").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { Er ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ToString() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { ToString = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS1913: Member 'ToString' cannot be initialized. It is not a field or property. // var b = a with { ToString = Identity(20) }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "ToString").WithArguments("ToString").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { To ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NestedInitializer() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var nested = new { A = 10 }; var a = new { Nested = nested }; var b = a with { Nested = { A = 20 } }; System.Console.Write(b); }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (10,35): error CS1525: Invalid expression term '{' // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(10, 35), // (10,35): error CS1513: } expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(10, 35), // (10,35): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(10, 35), // (10,37): error CS0103: The name 'A' does not exist in the current context // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(10, 37), // (10,44): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(10, 44), // (10,47): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(10, 47), // (11,29): error CS1519: Invalid token '(' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "(").WithArguments("(").WithLocation(11, 29), // (11,31): error CS8124: Tuple must contain at least two elements. // System.Console.Write(b); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(11, 31), // (11,32): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(11, 32), // (13,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> nested] [<anonymous type: <anonymous type: System.Int32 A> Nested> a] [<anonymous type: <anonymous type: System.Int32 A> Nested> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Left: ILocalReferenceOperation: nested (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'nested') Value: ILocalReferenceOperation: nested (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'nested') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'new { Nested = nested }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested = nested') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'new { Nested = nested }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested') Next (Regular) Block[B3] Leaving: {R3} Entering: {R4} } .locals {R4} { CaptureIds: [2] Block[B3] - Block Predecessors: [B2] Statements (3) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '') Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid) (Syntax: 'a with { Nested = ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R4} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'A = 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'A = 20') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'A') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NonAssignmentExpression() { var src = @" public class C { public static void M(int i, int j) /*<bind>*/{ var a = new { A = 10 }; var b = a with { i, j++, M2(), A = 20 }; }/*</bind>*/ static int M2() => 0; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(7, 26), // (7,29): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(7, 29), // (7,34): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(7, 34) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (6) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 C.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { i, ... ), A = 20 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_IndexerAccess() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { [0] = 20 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (7,26): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "[").WithLocation(7, 26), // (7,26): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "[").WithLocation(7, 26), // (7,26): error CS7014: Attributes are not valid in this context. // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[").WithLocation(7, 26), // (7,27): error CS1001: Identifier expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_IdentifierExpected, "0").WithLocation(7, 27), // (7,27): error CS1003: Syntax error, ']' expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SyntaxError, "0").WithArguments("]", "").WithLocation(7, 27), // (7,28): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "]").WithLocation(7, 28), // (7,28): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "]").WithLocation(7, 28), // (7,30): error CS1525: Invalid expression term '=' // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 30), // (7,35): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 35), // (7,36): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(7, 36), // (9,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(9, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { ') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '[0') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '= 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '= 20') Left: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_CannotSet() { var src = @" public class C { public static void M() { var a = new { A = 10 }; a.A = 20; var b = new { B = a }; b.B.A = 30; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // a.A = 20; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "a.A").WithArguments("<anonymous type: int A>.A").WithLocation(7, 9), // (10,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // b.B.A = 30; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.B.A").WithArguments("<anonymous type: int A>.A").WithLocation(10, 9) ); } [Fact] public void WithExpr_AnonymousType_DuplicateMemberInDeclaration() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10, A = 20 }; var b = Identity(a) with { A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (6,31): error CS0833: An anonymous type cannot have multiple properties with the same name // var a = new { A = 10, A = 20 }; Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "A = 20").WithLocation(6, 31) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 $1> a] [<anonymous type: System.Int32 A, System.Int32 $1> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid) (Syntax: 'new { A = 10, A = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: 'A = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsInvalid, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 $1> C.Identity<<anonymous type: System.Int32 A, System.Int32 $1>>(<anonymous type: System.Int32 A, System.Int32 $1> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_DuplicateInitialization() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = Identity(a) with { A = Identity(30), A = Identity(40) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (7,54): error CS1912: Duplicate initialization of member 'A' // var b = Identity(a) with { A = Identity(30), A = Identity(40) }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "A").WithArguments("A").WithLocation(7, 54) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A> C.Identity<<anonymous type: System.Int32 A>>(<anonymous type: System.Int32 A> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo() { var src = @" var x = new { Property = 42 }; var adjusted = x with { Property = x.Property + 2 }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Property = 44 }"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo_NestedWith() { var src = @" var x = new { Property = 42 }; var container = new { Item = x }; var adjusted = container with { Item = x with { Property = x.Property + 2 } }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Item = { Property = 44 } }"); verifier.VerifyDiagnostics(); } [Fact] public void AttributesOnPrimaryConstructorParameters_01() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public readonly record struct Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.RegularPreview, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => a.AttributeClass!.Name is "A" or "B" or "C" or "D")); } } [Fact] public void FieldAsPositionalMember() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record struct A(int X) { public int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(8, 8), // (8,17): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 17) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_Readonly() { var source = @" readonly record struct A(int X) { public int X = X; // 1 } readonly record struct B(int X) { public readonly int X = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS8340: Instance fields of readonly structs must be readonly. // public int X = X; // 1 Diagnostic(ErrorCode.ERR_FieldsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void FieldAsPositionalMember_Fixed() { var src = @" unsafe record struct C(int[] P) { public fixed int P[2]; public int[] X = P; }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,30): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int[]' to match positional parameter 'P'. // unsafe record struct C(int[] P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int[]", "P").WithLocation(2, 30), // (4,22): error CS8908: The type 'int*' may not be used for a field of a record. // public fixed int P[2]; Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P").WithArguments("int*").WithLocation(4, 22) ); } [Fact] public void FieldAsPositionalMember_WrongType() { var source = @" record struct A(int X) { public string X = null; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,21): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record struct A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 21) ); } [Fact] public void FieldAsPositionalMember_DuplicateFields() { var source = @" record struct A(int X) { public int X = 0; public int X = 0; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS0102: The type 'A' already contains a definition for 'X' // public int X = 0; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("A", "X").WithLocation(5, 16) ); } [Fact] public void SyntaxFactory_TypeDeclaration() { var expected = @"record struct Point { }"; AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, SyntaxFactory.TypeDeclaration(SyntaxKind.RecordStructDeclaration, "Point").NormalizeWhitespace().ToString()); } [Fact] public void InterfaceWithParameters() { var src = @" public interface I { } record struct R(int X) : I() { } record struct R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,27): error CS8861: Unexpected argument list. // record struct R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 27), // (10,28): error CS8861: Unexpected argument list. // record struct R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 28) ); } [Fact] public void InterfaceWithParameters_NoPrimaryConstructor() { var src = @" public interface I { } record struct R : I() { } record struct R2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,20): error CS8861: Unexpected argument list. // record struct R : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20), // (10,21): error CS8861: Unexpected argument list. // record struct R2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 21) ); } [Fact] public void InterfaceWithParameters_Struct() { var src = @" public interface I { } struct C : I() { } struct C2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,13): error CS8861: Unexpected argument list. // struct C : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13), // (10,14): error CS8861: Unexpected argument list. // struct C2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14) ); } [Fact] public void BaseArguments_Speculation() { var src = @" record struct R1(int X) : Error1(0, 1) { } record struct R2(int X) : Error2() { } record struct R3(int X) : Error3 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,27): error CS0246: The type or namespace name 'Error1' could not be found (are you missing a using directive or an assembly reference?) // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error1").WithArguments("Error1").WithLocation(2, 27), // (2,33): error CS8861: Unexpected argument list. // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0, 1)").WithLocation(2, 33), // (5,27): error CS0246: The type or namespace name 'Error2' could not be found (are you missing a using directive or an assembly reference?) // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error2").WithArguments("Error2").WithLocation(5, 27), // (5,33): error CS8861: Unexpected argument list. // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(5, 33), // (8,27): error CS0246: The type or namespace name 'Error3' could not be found (are you missing a using directive or an assembly reference?) // record struct R3(int X) : Error3 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error3").WithArguments("Error3").WithLocation(8, 27) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().First(); Assert.Equal("Error1(0, 1)", baseWithargs.ToString()); var speculativeBase = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); Assert.Equal("Error1(0)", speculativeBase.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Skip(1).First(); Assert.Equal("Error2()", baseWithoutargs.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutParens = tree.GetRoot().DescendantNodes().OfType<SimpleBaseTypeSyntax>().Single(); Assert.Equal("Error3", baseWithoutParens.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutParens.SpanStart + 2, speculativeBase, out _)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.RecordStructs)] public class RecordStructTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); private CompilationVerifier CompileAndVerify( CSharpTestSource src, string? expectedOutput = null, IEnumerable<MetadataReference>? references = null) => base.CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.RegularPreview, references: references, // init-only is unverifiable verify: Verification.Skipped); [Fact] public void StructRecord1() { var src = @" record struct Point(int X, int Y);"; var verifier = CompileAndVerify(src).VerifyDiagnostics(); verifier.VerifyIL("Point.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""Point"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""Point"" IL_000f: call ""readonly bool Point.Equals(Point)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("Point.Equals(Point)", @" { // Code size 49 (0x31) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int Point.<X>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int Point.<X>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_002f IL_0018: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""int Point.<Y>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""int Point.<Y>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002e: ret IL_002f: ldc.i4.0 IL_0030: ret }"); } [Fact] public void StructRecord2() { var src = @" using System; record struct S(int X, int Y) { public static void Main() { var s1 = new S(0, 1); var s2 = new S(0, 1); Console.WriteLine(s1.X); Console.WriteLine(s1.Y); Console.WriteLine(s1.Equals(s2)); Console.WriteLine(s1.Equals(new S(1, 0))); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 True False").VerifyDiagnostics(); } [Fact] public void StructRecord3() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) => false; public static void Main() { var s1 = new S(0, 1); Console.WriteLine(s1.Equals(s1)); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"False") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); verifier.VerifyIL("S.Main", @" { // Code size 23 (0x17) .maxstack 3 .locals init (S V_0) //s1 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""S..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloc.0 IL_000c: call ""bool S.Equals(S)"" IL_0011: call ""void System.Console.WriteLine(bool)"" IL_0016: ret }"); } [Fact] public void StructRecord5() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) { Console.Write(""s""); return true; } public static void Main() { var s1 = new S(0, 1); s1.Equals((object)s1); s1.Equals(s1); } }"; CompileAndVerify(src, expectedOutput: @"ss") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); } [Fact] public void StructRecordDefaultCtor() { const string src = @" public record struct S(int X);"; const string src2 = @" class C { public S M() => new S(); }"; var comp = CreateCompilation(src + src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src); var comp2 = CreateCompilation(src2, references: new[] { comp.EmitToImageReference() }); comp2.VerifyDiagnostics(); } [Fact] public void Equality_01() { var source = @"using static System.Console; record struct S; class Program { static void Main() { var x = new S(); var y = new S(); WriteLine(x.Equals(y)); WriteLine(((object)x).Equals(y)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True True").VerifyDiagnostics(); verifier.VerifyIL("S.Equals(S)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("S.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""S"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""S"" IL_000f: call ""readonly bool S.Equals(S)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); } [Fact] public void RecordStructLanguageVersion() { var src1 = @" struct Point(int x, int y); "; var src2 = @" record struct Point { } "; var src3 = @" record struct Point(int x, int y); "; var comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void RecordStructLanguageVersion_Nested() { var src1 = @" class C { struct Point(int x, int y); } "; var src2 = @" class D { record struct Point { } } "; var src3 = @" struct E { record struct Point(int x, int y); } "; var src4 = @" namespace NS { record struct Point { } } "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src1); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); comp = CreateCompilation(src4); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_IsStruct() { var src = @" record struct Point(int x, int y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.Equal("Point", point.ToTestDisplayString()); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); Assert.Equal("record struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); Assert.Equal("struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } } } [Fact] public void TypeDeclaration_IsStruct_InConstraints() { var src = @" record struct Point(int x, int y); class C<T> where T : struct { void M(C<Point> c) { } } class C2<T> where T : new() { void M(C2<Point> c) { } } class C3<T> where T : class { void M(C3<Point> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (16,22): error CS0452: The type 'Point' must be a reference type in order to use it as parameter 'T' in the generic type or method 'C3<T>' // void M(C3<Point> c) { } // 1 Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "c").WithArguments("C3<T>", "T", "Point").WithLocation(16, 22) ); } [Fact] public void TypeDeclaration_IsStruct_Unmanaged() { var src = @" record struct Point(int x, int y); record struct Point2(string x, string y); class C<T> where T : unmanaged { void M(C<Point> c) { } void M2(C<Point2> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,23): error CS8377: The type 'Point2' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C<T>' // void M2(C<Point2> c) { } // 1 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("C<T>", "T", "Point2").WithLocation(8, 23) ); } [Fact] public void IsRecord_Generic() { var src = @" record struct Point<T>(T x, T y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); } } } [Fact] public void IsRecord_Retargeting() { var src = @" public record struct Point(int x, int y); "; var comp = CreateCompilation(src, targetFramework: TargetFramework.Mscorlib40); var comp2 = CreateCompilation("", targetFramework: TargetFramework.Mscorlib46, references: new[] { comp.ToMetadataReference() }); var point = comp2.GlobalNamespace.GetTypeMember("Point"); Assert.Equal("Point", point.ToTestDisplayString()); Assert.IsType<RetargetingNamedTypeSymbol>(point); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } [Fact] public void IsRecord_AnonymousType() { var src = @" class C { void M() { var x = new { X = 1 }; } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var creation = tree.GetRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>().Single(); var type = model.GetTypeInfo(creation).Type!; Assert.Equal("<anonymous type: System.Int32 X>", type.ToTestDisplayString()); Assert.IsType<AnonymousTypeManager.AnonymousTypePublicSymbol>(((Symbols.PublicModel.NonErrorNamedTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_ErrorType() { var src = @" class C { Error M() => throw null; } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("Error", type.ToTestDisplayString()); Assert.IsType<ExtendedErrorTypeSymbol>(((Symbols.PublicModel.ErrorTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Pointer() { var src = @" class C { int* M() => throw null; } "; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("System.Int32*", type.ToTestDisplayString()); Assert.IsType<PointerTypeSymbol>(((Symbols.PublicModel.PointerTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Dynamic() { var src = @" class C { void M(dynamic d) { } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.GetParameterType(0); Assert.Equal("dynamic", type.ToTestDisplayString()); Assert.IsType<DynamicTypeSymbol>(((Symbols.PublicModel.DynamicTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void TypeDeclaration_MayNotHaveBaseType() { var src = @" record struct Point(int x, int y) : object; record struct Point2(int x, int y) : System.ValueType; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,37): error CS0527: Type 'object' in interface list is not an interface // record struct Point(int x, int y) : object; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "object").WithArguments("object").WithLocation(2, 37), // (3,38): error CS0527: Type 'ValueType' in interface list is not an interface // record struct Point2(int x, int y) : System.ValueType; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "System.ValueType").WithArguments("System.ValueType").WithLocation(3, 38) ); } [Fact] public void TypeDeclaration_MayNotHaveTypeConstraintsWithoutTypeParameters() { var src = @" record struct Point(int x, int y) where T : struct; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,35): error CS0080: Constraints are not allowed on non-generic declarations // record struct Point(int x, int y) where T : struct; Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(2, 35) ); } [Fact] public void TypeDeclaration_AllowedModifiers() { var src = @" readonly partial record struct S1; public record struct S2; internal record struct S3; public class Base { public int S6; } public class C : Base { private protected record struct S4; protected internal record struct S5; new record struct S6; } unsafe record struct S7; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics(); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S1").DeclaredAccessibility); Assert.Equal(Accessibility.Public, comp.GlobalNamespace.GetTypeMember("S2").DeclaredAccessibility); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S3").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedAndInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S4").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S5").DeclaredAccessibility); } [Fact] public void TypeDeclaration_DisallowedModifiers() { var src = @" abstract record struct S1; volatile record struct S2; extern record struct S3; virtual record struct S4; override record struct S5; async record struct S6; ref record struct S7; unsafe record struct S8; static record struct S9; sealed record struct S10; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS0106: The modifier 'abstract' is not valid for this item // abstract record struct S1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S1").WithArguments("abstract").WithLocation(2, 24), // (3,24): error CS0106: The modifier 'volatile' is not valid for this item // volatile record struct S2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S2").WithArguments("volatile").WithLocation(3, 24), // (4,22): error CS0106: The modifier 'extern' is not valid for this item // extern record struct S3; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S3").WithArguments("extern").WithLocation(4, 22), // (5,23): error CS0106: The modifier 'virtual' is not valid for this item // virtual record struct S4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S4").WithArguments("virtual").WithLocation(5, 23), // (6,24): error CS0106: The modifier 'override' is not valid for this item // override record struct S5; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S5").WithArguments("override").WithLocation(6, 24), // (7,21): error CS0106: The modifier 'async' is not valid for this item // async record struct S6; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S6").WithArguments("async").WithLocation(7, 21), // (8,19): error CS0106: The modifier 'ref' is not valid for this item // ref record struct S7; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S7").WithArguments("ref").WithLocation(8, 19), // (9,22): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe record struct S8; Diagnostic(ErrorCode.ERR_IllegalUnsafe, "S8").WithLocation(9, 22), // (10,22): error CS0106: The modifier 'static' is not valid for this item // static record struct S9; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S9").WithArguments("static").WithLocation(10, 22), // (11,22): error CS0106: The modifier 'sealed' is not valid for this item // sealed record struct S10; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S10").WithArguments("sealed").WithLocation(11, 22) ); } [Fact] public void TypeDeclaration_DuplicatesModifiers() { var src = @" public public record struct S2; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): error CS1004: Duplicate 'public' modifier // public public record struct S2; Diagnostic(ErrorCode.ERR_DuplicateModifier, "public").WithArguments("public").WithLocation(2, 8) ); } [Fact] public void TypeDeclaration_BeforeTopLevelStatement() { var src = @" record struct S; System.Console.WriteLine(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine();").WithLocation(3, 1) ); } [Fact] public void TypeDeclaration_WithTypeParameters() { var src = @" S<string> local = default; local.ToString(); record struct S<T>; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); Assert.Equal(new[] { "T" }, comp.GlobalNamespace.GetTypeMember("S").TypeParameters.ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_AllowedModifiersForMembers() { var src = @" record struct S { protected int Property { get; set; } // 1 internal protected string field; // 2, 3 abstract void M(); // 4 virtual void M2() { } // 5 }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0666: 'S.Property': new protected member declared in struct // protected int Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Property").WithArguments("S.Property").WithLocation(4, 19), // (5,31): error CS0666: 'S.field': new protected member declared in struct // internal protected string field; // 2, 3 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "field").WithArguments("S.field").WithLocation(5, 31), // (5,31): warning CS0649: Field 'S.field' is never assigned to, and will always have its default value null // internal protected string field; // 2, 3 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("S.field", "null").WithLocation(5, 31), // (6,19): error CS0621: 'S.M()': virtual or abstract members cannot be private // abstract void M(); // 4 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M").WithArguments("S.M()").WithLocation(6, 19), // (7,18): error CS0621: 'S.M2()': virtual or abstract members cannot be private // virtual void M2() { } // 5 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M2").WithArguments("S.M2()").WithLocation(7, 18) ); } [Fact] public void TypeDeclaration_ImplementInterface() { var src = @" I i = (I)default(S); System.Console.Write(i.M(""four"")); I i2 = (I)default(S2); System.Console.Write(i2.M(""four"")); interface I { int M(string s); } public record struct S : I { public int M(string s) => s.Length; } public record struct S2 : I { int I.M(string s) => s.Length + 1; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "45"); AssertEx.Equal(new[] { "System.Int32 S.M(System.String s)", "readonly System.String S.ToString()", "readonly System.Boolean S.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean S.op_Inequality(S left, S right)", "System.Boolean S.op_Equality(S left, S right)", "readonly System.Int32 S.GetHashCode()", "readonly System.Boolean S.Equals(System.Object obj)", "readonly System.Boolean S.Equals(S other)", "S..ctor()" }, comp.GetMember<NamedTypeSymbol>("S").GetMembers().ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_SatisfiesStructConstraint() { var src = @" S s = default; System.Console.Write(M(s)); static int M<T>(T t) where T : struct, I => t.Property; public interface I { int Property { get; } } public record struct S : I { public int Property => 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void TypeDeclaration_AccessingThis() { var src = @" S s = new S(); System.Console.Write(s.M()); public record struct S { public int Property => 42; public int M() => this.Property; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("S.M", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int S.Property.get"" IL_0006: ret } "); } [Fact] public void TypeDeclaration_NoBaseInitializer() { var src = @" public record struct S { public S(int i) : base() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,12): error CS0522: 'S': structs cannot call base class constructors // public S(int i) : base() { } Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, "S").WithArguments("S").WithLocation(4, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_01() { var src = @"record struct S0(); record struct S1; record struct S2 { public S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S0(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8), // (3,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(3, 8), // (5,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // public S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(5, 12)); var verifier = CompileAndVerify(src); verifier.VerifyIL("S0..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); verifier.VerifyMissing("S1..ctor()"); verifier.VerifyIL("S2..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [Fact] public void TypeDeclaration_ParameterlessConstructor_02() { var src = @"record struct S1 { S1() { } } record struct S2 { internal S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (3,5): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // S1() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S1").WithArguments("parameterless struct constructors", "10.0").WithLocation(3, 5), // (3,5): error CS8938: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (5,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(5, 8), // (7,14): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // internal S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(7, 14), // (7,14): error CS8938: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,5): error CS8918: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (7,14): error CS8918: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); } [Fact] public void TypeDeclaration_ParameterlessConstructor_OtherConstructors() { var src = @" record struct S1 { public S1() { } S1(object o) { } // ok because no record parameter list } record struct S2 { S2(object o) { } } record struct S3() { S3(object o) { } // 1 } record struct S4() { S4(object o) : this() { } } record struct S5(object o) { public S5() { } // 2 } record struct S6(object o) { public S6() : this(null) { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // S3(object o) { } // 1 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S3").WithLocation(13, 5), // (21,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public S5() { } // 2 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S5").WithLocation(21, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_Initializers() { var src = @" var s1 = new S1(); var s2 = new S2(null); var s2b = new S2(); var s3 = new S3(); var s4 = new S4(new object()); var s5 = new S5(); var s6 = new S6(""s6.other""); System.Console.Write((s1.field, s2.field, s2b.field is null, s3.field, s4.field, s5.field, s6.field, s6.other)); record struct S1 { public string field = ""s1""; public S1() { } } record struct S2 { public string field = ""s2""; public S2(object o) { } } record struct S3() { public string field = ""s3""; } record struct S4 { public string field = ""s4""; public S4(object o) : this() { } } record struct S5() { public string field = ""s5""; public S5(object o) : this() { } } record struct S6(string other) { public string field = ""s6.field""; public S6() : this(""ignored"") { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(s1, s2, True, s3, s4, s5, s6.field, s6.other)"); } [Fact] public void TypeDeclaration_InstanceInitializers() { var src = @" public record struct S { public int field = 42; public int Property { get; set; } = 43; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // public record struct S Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 15), // (4,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int field = 42; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "field").WithArguments("struct field initializers", "10.0").WithLocation(4, 16), // (5,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int Property { get; set; } = 43; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Property").WithArguments("struct field initializers", "10.0").WithLocation(5, 16)); comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_NoDestructor() { var src = @" public record struct S { ~S() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,6): error CS0575: Only class types can contain destructors // ~S() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "S").WithArguments("S.~S()").WithLocation(4, 6) ); } [Fact] public void TypeDeclaration_DifferentPartials() { var src = @" partial record struct S1; partial struct S1 { } partial struct S2 { } partial record struct S2; partial record struct S3; partial record S3 { } partial record struct S4; partial record class S4 { } partial record struct S5; partial class S5 { } partial record struct S6; partial interface S6 { } partial record class C1; partial struct C1 { } partial record class C2; partial record struct C2 { } partial record class C3 { } partial record C3; partial record class C4; partial class C4 { } partial record class C5; partial interface C5 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,16): error CS0261: Partial declarations of 'S1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct S1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S1").WithArguments("S1").WithLocation(3, 16), // (6,23): error CS0261: Partial declarations of 'S2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct S2; Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S2").WithArguments("S2").WithLocation(6, 23), // (9,16): error CS0261: Partial declarations of 'S3' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record S3 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S3").WithArguments("S3").WithLocation(9, 16), // (12,22): error CS0261: Partial declarations of 'S4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record class S4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S4").WithArguments("S4").WithLocation(12, 22), // (15,15): error CS0261: Partial declarations of 'S5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class S5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S5").WithArguments("S5").WithLocation(15, 15), // (18,19): error CS0261: Partial declarations of 'S6' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface S6 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S6").WithArguments("S6").WithLocation(18, 19), // (21,16): error CS0261: Partial declarations of 'C1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct C1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C1").WithArguments("C1").WithLocation(21, 16), // (24,23): error CS0261: Partial declarations of 'C2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct C2 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C2").WithArguments("C2").WithLocation(24, 23), // (30,15): error CS0261: Partial declarations of 'C4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class C4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C4").WithArguments("C4").WithLocation(30, 15), // (33,19): error CS0261: Partial declarations of 'C5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface C5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C5").WithArguments("C5").WithLocation(33, 19) ); } [Fact] public void PartialRecord_OnlyOnePartialHasParameterList() { var src = @" partial record struct S(int i); partial record struct S(int i); partial record struct S2(int i); partial record struct S2(); partial record struct S3(); partial record struct S3(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,24): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S(int i); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int i)").WithLocation(3, 24), // (6,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S2(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(6, 25), // (9,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S3(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(9, 25) ); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record struct C(int X) { public int P1 { get; set; } = X; } public partial record struct C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */) .VerifyDiagnostics( // (5,30): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'C'. To specify an ordering, all instance fields must be in the same declaration. // public partial record struct C(int X) Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "C").WithArguments("C").WithLocation(5, 30) ); } [Fact] public void PartialRecord_DuplicateMemberNames() { var src = @" public partial record struct C(int X) { public void M(int i) { } } public partial record struct C { public void M(string s) { } } "; var comp = CreateCompilation(src); var expectedMemberNames = new string[] { ".ctor", "<X>k__BackingField", "get_X", "set_X", "X", "M", "M", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "Deconstruct", ".ctor", }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordInsideGenericType() { var src = @" var c = new C<int>.Nested(2); System.Console.Write(c.T); public class C<T> { public record struct Nested(T T); } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void PositionalMemberModifiers_RefOrOut() { var src = @" record struct R(ref int P1, out int P2); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,15): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 15), // (2,17): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 17), // (2,29): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 29) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_This() { var src = @" record struct R(this int i); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0027: Keyword 'this' is not available in the current context // record struct R(this int i); Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 17) ); } [Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")] public void Clone_DisallowedInSource() { var src = @" record struct C1(string Clone); // 1 record struct C2 { string Clone; // 2 } record struct C3 { string Clone { get; set; } // 3 } record struct C5 { void Clone() { } // 4 void Clone(int i) { } // 5 } record struct C6 { class Clone { } // 6 } record struct C7 { delegate void Clone(); // 7 } record struct C8 { event System.Action Clone; // 8 } record struct Clone { Clone(int i) => throw null; } record struct C9 : System.ICloneable { object System.ICloneable.Clone() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,25): error CS8859: Members named 'Clone' are disallowed in records. // record struct C1(string Clone); // 1 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 25), // (5,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone; // 2 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(5, 12), // (5,12): warning CS0169: The field 'C2.Clone' is never used // string Clone; // 2 Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C2.Clone").WithLocation(5, 12), // (9,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone { get; set; } // 3 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(9, 12), // (13,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone() { } // 4 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 10), // (14,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone(int i) { } // 5 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(14, 10), // (18,11): error CS8859: Members named 'Clone' are disallowed in records. // class Clone { } // 6 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 11), // (22,19): error CS8859: Members named 'Clone' are disallowed in records. // delegate void Clone(); // 7 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 19), // (26,25): error CS8859: Members named 'Clone' are disallowed in records. // event System.Action Clone; // 8 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 25), // (26,25): warning CS0067: The event 'C8.Clone' is never used // event System.Action Clone; // 8 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(26, 25) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes() { var src = @" class C<T> { } static class C2 { } ref struct RefLike{} unsafe record struct C( // 1 int* P1, // 2 int*[] P2, // 3 C<int*[]> P3, delegate*<int, int> P4, // 4 void P5, // 5 C2 P6, // 6, 7 System.ArgIterator P7, // 8 System.TypedReference P8, // 9 RefLike P9); // 10 "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (6,22): error CS0721: 'C2': static types cannot be used as parameters // unsafe record struct C( // 1 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 22), // (7,10): error CS8908: The type 'int*' may not be used for a field of a record. // int* P1, // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P1").WithArguments("int*").WithLocation(7, 10), // (8,12): error CS8908: The type 'int*[]' may not be used for a field of a record. // int*[] P2, // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P2").WithArguments("int*[]").WithLocation(8, 12), // (10,25): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // delegate*<int, int> P4, // 4 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P4").WithArguments("delegate*<int, int>").WithLocation(10, 25), // (11,5): error CS1536: Invalid parameter type 'void' // void P5, // 5 Diagnostic(ErrorCode.ERR_NoVoidParameter, "void").WithLocation(11, 5), // (12,8): error CS0722: 'C2': static types cannot be used as return types // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (12,8): error CS0721: 'C2': static types cannot be used as parameters // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (13,5): error CS0610: Field or property cannot be of type 'ArgIterator' // System.ArgIterator P7, // 8 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 5), // (14,5): error CS0610: Field or property cannot be of type 'TypedReference' // System.TypedReference P8, // 9 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 5), // (15,5): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // RefLike P9); // 10 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 5) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record struct C { public int* f1; // 1 public int*[] f2; // 2 public C<int*[]> f3; public delegate*<int, int> f4; // 3 public void f5; // 4 public C2 f6; // 5 public System.ArgIterator f7; // 6 public System.TypedReference f8; // 7 public RefLike f9; // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1; // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2; // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4; // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,12): error CS0670: Field cannot have void type // public void f5; // 4 Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(12, 12), // (13,15): error CS0723: Cannot declare a variable of static type 'C2' // public C2 f6; // 5 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(13, 15), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7; // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8; // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9; // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers_AutoProperties() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record struct C { public int* f1 { get; set; } // 1 public int*[] f2 { get; set; } // 2 public C<int*[]> f3 { get; set; } public delegate*<int, int> f4 { get; set; } // 3 public void f5 { get; set; } // 4 public C2 f6 { get; set; } // 5, 6 public System.ArgIterator f7 { get; set; } // 6 public System.TypedReference f8 { get; set; } // 7 public RefLike f9 { get; set; } // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1 { get; set; } // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2 { get; set; } // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4 { get; set; } // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,17): error CS0547: 'C.f5': property or indexer cannot have void type // public void f5 { get; set; } // 4 Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "f5").WithArguments("C.f5").WithLocation(12, 17), // (13,20): error CS0722: 'C2': static types cannot be used as return types // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("C2").WithLocation(13, 20), // (13,25): error CS0721: 'C2': static types cannot be used as parameters // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("C2").WithLocation(13, 25), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7 { get; set; } // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8 { get; set; } // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9 { get; set; } // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [Fact] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_PointerTypeAllowedForParameterAndProperty() { var src = @" class C<T> { } unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) { int* P1 { get { System.Console.Write(""P1 ""); return null; } init { } } int*[] P2 { get { System.Console.Write(""P2 ""); return null; } init { } } C<int*[]> P3 { get { System.Console.Write(""P3 ""); return null; } init { } } public unsafe static void Main() { var x = new C(null, null, null); var (x1, x2, x3) = x; System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugExe); comp.VerifyEmitDiagnostics( // (4,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 29), // (4,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 40), // (4,54): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 54) ); CompileAndVerify(comp, expectedOutput: "P1 P2 P3 RAN", verify: Verification.Skipped /* pointers */); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_StaticFields() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public static int* f1; public static int*[] f2; public static C<int*[]> f3; public static delegate*<int, int> f4; public static C2 f6; // 1 public static System.ArgIterator f7; // 2 public static System.TypedReference f8; // 3 public static RefLike f9; // 4 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (12,22): error CS0723: Cannot declare a variable of static type 'C2' // public static C2 f6; // 1 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(12, 22), // (13,19): error CS0610: Field or property cannot be of type 'ArgIterator' // public static System.ArgIterator f7; // 2 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 19), // (14,19): error CS0610: Field or property cannot be of type 'TypedReference' // public static System.TypedReference f8; // 3 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 19), // (15,19): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public static RefLike f9; // 4 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 19) ); } [Fact] public void RecordProperties_01() { var src = @" using System; record struct C(int X, int Y) { int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 26 (0x1a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4 0x159 IL_0014: stfld ""int C.Z"" IL_0019: ret } "); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.False(c.IsReadOnly); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("readonly System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void C.X.set", x.SetMethod.ToTestDisplayString()); Assert.False(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.False(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_01_EmptyParameterList() { var src = @" using System; record struct C() { int Z = 345; public static void Main() { var c = new C(); Console.Write(c.Z); } }"; CreateCompilation(src).VerifyEmitDiagnostics(); } [Fact] public void RecordProperties_01_Readonly() { var src = @" using System; readonly record struct C(int X, int Y) { readonly int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.True(c.IsReadOnly); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", x.SetMethod.ToTestDisplayString()); Assert.True(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.True(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_01_ReadonlyMismatch() { var src = @" readonly record struct C(int X) { public int X { get; set; } = X; // 1 } record struct C2(int X) { public int X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,16): error CS8341: Auto-implemented instance properties in readonly structs must be readonly. // public int X { get; set; } = X; // 1 Diagnostic(ErrorCode.ERR_AutoPropsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void RecordProperties_02() { var src = @" using System; record struct C(int X, int Y) { public C(int a, int b) { } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } private int X1 = X; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C(int a, int b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(5, 12), // (5,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, int b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(5, 12), // (11,21): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(int, int)' and 'C.C(int, int)' // var c = new C(1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "C").WithArguments("C.C(int, int)", "C.C(int, int)").WithLocation(11, 21) ); } [Fact] public void RecordProperties_03() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,15): error CS0843: Auto-implemented property 'C.X' must be fully assigned before control is returned to the caller. // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C").WithArguments("C.X").WithLocation(3, 15), // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_03_InitializedWithY() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = Y; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "22") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_04() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = 3; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "32") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_05() { var src = @" record struct C(int X, int X) { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,28): error CS0100: The parameter name 'X' is a duplicate // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 28), // (2,28): error CS0102: The type 'C' already contains a definition for 'X' // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 28) ); var expectedMembers = new[] { "System.Int32 C.X { get; set; }", "System.Int32 C.X { get; set; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "Deconstruct", ".ctor" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_06() { var src = @" record struct C(int X, int Y) { public void get_X() { } public void set_X() { } int get_Y(int value) => value; int set_Y(int value) => value; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 21), // (2,28): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 28) ); var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Int32 C.<X>k__BackingField", "readonly System.Int32 C.X.get", "void C.X.set", "System.Int32 C.X { get; set; }", "System.Int32 C.<Y>k__BackingField", "readonly System.Int32 C.Y.get", "void C.Y.set", "System.Int32 C.Y { get; set; }", "void C.get_X()", "void C.set_X()", "System.Int32 C.get_Y(System.Int32 value)", "System.Int32 C.set_Y(System.Int32 value)", "readonly System.String C.ToString()", "readonly System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "readonly System.Int32 C.GetHashCode()", "readonly System.Boolean C.Equals(System.Object obj)", "readonly System.Boolean C.Equals(C other)", "readonly void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", "C..ctor()", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void RecordProperties_07() { var comp = CreateCompilation(@" record struct C1(object P, object get_P); record struct C2(object get_P, object P);"); comp.VerifyDiagnostics( // (2,25): error CS0102: The type 'C1' already contains a definition for 'get_P' // record struct C1(object P, object get_P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 25), // (3,39): error CS0102: The type 'C2' already contains a definition for 'get_P' // record struct C2(object get_P, object P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 39) ); } [Fact] public void RecordProperties_08() { var comp = CreateCompilation(@" record struct C1(object O1) { public object O1 { get; } = O1; public object O2 { get; } = O1; }"); comp.VerifyDiagnostics(); } [Fact] public void RecordProperties_09() { var src = @" record struct C(object P1, object P2, object P3, object P4) { class P1 { } object P2 = 2; int P3(object o) => 3; int P4<T>(T t) => 4; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS0102: The type 'C' already contains a definition for 'P1' // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(2, 24), // (2,35): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(2, 35), // (6,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(6, 9), // (7,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(7, 9) ); } [Fact] public void RecordProperties_10() { var src = @" record struct C(object P) { const int P = 4; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record struct C(object P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "object", "P").WithLocation(2, 24), // (2,24): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 24) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter() { var comp = CreateCompilation(@" record struct C1(object O1, object O2, object O3) // 1, 2 { public object O1 { get; init; } public object O2 { get; init; } = M(O2); public object O3 { get; init; } = M(O3 = null); private static object M(object o) => o; } "); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'C1.O1' must be fully assigned before control is returned to the caller. // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C1").WithArguments("C1.O1").WithLocation(2, 15), // (2,25): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 25), // (2,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter_InRefOut() { var comp = CreateCompilation(@" record struct C1(object O1, object O2, object O3) // 1 { public object O1 { get; init; } = MIn(in O1); public object O2 { get; init; } = MRef(ref O2); public object O3 { get; init; } = MOut(out O3); static object MIn(in object o) => o; static object MRef(ref object o) => o; static object MOut(out object o) => throw null; } "); comp.VerifyDiagnostics( // (2,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_SelfContainedStruct() { var comp = CreateCompilation(@" record struct C(C c); "); comp.VerifyDiagnostics( // (2,19): error CS0523: Struct member 'C.c' of type 'C' causes a cycle in the struct layout // record struct C(C c); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "c").WithArguments("C.c", "C").WithLocation(2, 19) ); } [Fact] public void RecordProperties_PropertyInValueType() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); { var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } { var src = @" readonly record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,31): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // readonly record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 31) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } } [Fact] public void RecordProperties_PropertyInValueType_Static() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public static bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): error CS8866: Record member 'System.ValueType.X' must be a readable instance property or field of type 'bool' to match positional parameter 'X'. // record struct C(bool X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("System.ValueType.X", "bool", "X").WithLocation(2, 22), // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); } [Fact] public void StaticCtor() { var src = @" record R(int x) { static void Main() { } static R() { System.Console.Write(""static ctor""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped /* init-only */); } [Fact] public void StaticCtor_ParameterlessPrimaryCtor() { var src = @" record struct R(int I) { static R() { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void StaticCtor_CopyCtor() { var src = @" record struct R(int I) { static R(R r) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0132: 'R.R(R)': a static constructor must be parameterless // static R(R r) { } Diagnostic(ErrorCode.ERR_StaticConstParam, "R").WithArguments("R.R(R)").WithLocation(4, 12) ); } [Fact] public void InterfaceImplementation_NotReadonly() { var source = @" I r = new R(42); r.P2 = 43; r.P3 = 44; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; set; } int P2 { get; set; } int P3 { get; set; } } record struct R(int P1) : I { public int P2 { get; set; } = 0; int I.P3 { get; set; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44)"); } [Fact] public void InterfaceImplementation_NotReadonly_InitOnlyInterface() { var source = @" interface I { int P1 { get; init; } } record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,27): error CS8854: 'R' does not implement interface member 'I.P1.init'. 'R.P1.set' cannot implement 'I.P1.init'. // record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.init", "R.P1.set").WithLocation(6, 27) ); } [Fact] public void InterfaceImplementation_Readonly() { var source = @" I r = new R(42) { P2 = 43 }; System.Console.Write((r.P1, r.P2)); interface I { int P1 { get; init; } int P2 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */); } [Fact] public void InterfaceImplementation_Readonly_SetInterface() { var source = @" interface I { int P1 { get; set; } } readonly record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,36): error CS8854: 'R' does not implement interface member 'I.P1.set'. 'R.P1.init' cannot implement 'I.P1.set'. // readonly record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.set", "R.P1.init").WithLocation(6, 36) ); } [Fact] public void InterfaceImplementation_Readonly_PrivateImplementation() { var source = @" I r = new R(42) { P2 = 43, P3 = 44 }; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; init; } int P2 { get; init; } int P3 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; int I.P3 { get; init; } = 0; // not practically initializable } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,28): error CS0117: 'R' does not contain a definition for 'P3' // I r = new R(42) { P2 = 43, P3 = 44 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "P3").WithArguments("R", "P3").WithLocation(2, 28) ); } [Fact] public void Initializers_01() { var src = @" using System; record struct C(int X) { int Z = X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Single(); Assert.Equal("C", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); } [Fact] public void Initializers_02() { var src = @" record struct C(int X) { static int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,20): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // static int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 20) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; set; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_03() { var src = @" record struct C(int X) { const int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // const int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; set; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_04() { var src = @" using System; record struct C(int X) { Func<int> Z = () => X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("() => X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("lambda expression", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void SynthesizedRecordPointerProperty() { var src = @" record struct R(int P1, int* P2, delegate*<int> P3);"; var comp = CreateCompilation(src); var p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P1"); Assert.False(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P2"); Assert.True(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P3"); Assert.True(p.HasPointerType); } [Fact] public void PositionalMemberModifiers_In() { var src = @" var r = new R(42); int i = 43; var r2 = new R(in i); System.Console.Write((r.P1, r2.P1)); record struct R(in int P1); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "(42, 43)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(in System.Int32 P1)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberModifiers_Params() { var src = @" var r = new R(42, 43); var r2 = new R(new[] { 44, 45 }); System.Console.Write((r.Array[0], r.Array[1], r2.Array[0], r2.Array[1])); record struct R(params int[] Array); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(params System.Int32[] Array)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberDefaultValue() { var src = @" var r = new R(); // This uses the parameterless constructor System.Console.Write(r.P); record struct R(int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "0"); } [Fact] public void PositionalMemberDefaultValue_PassingOneArgument() { var src = @" var r = new R(41); System.Console.Write(r.O); System.Console.Write("" ""); System.Console.Write(r.P); record struct R(int O, int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "41 42"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 1) { public int P { get; init; } = 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,28): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int O, int P = 1) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(5, 28) ); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldc.i4.s 42 IL_000a: stfld ""int R.<P>k__BackingField"" IL_000f: ret }"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer() { var src = @" record struct R(int P = 42) { public int P { get; init; } public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'R.P' must be fully assigned before control is returned to the caller. // record struct R(int P = 42) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "R").WithArguments("R.P").WithLocation(2, 15), // (2,21): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int P = 42) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 21) ); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 42) { public int P { get; init; } = P; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int R.<P>k__BackingField"" IL_000e: ret }"); } [Fact] public void RecordWithConstraints_NullableWarning() { var src = @" #nullable enable var r = new R<string?>(""R""); var r2 = new R2<string?>(""R2""); System.Console.Write((r.P, r2.P)); record struct R<T>(T P) where T : class; record struct R2<T>(T P) where T : class { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,15): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r = new R<string?>("R"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R<T>", "T", "string?").WithLocation(3, 15), // (4,17): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r2 = new R2<string?>("R2"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R2<T>", "T", "string?").WithLocation(4, 17) ); CompileAndVerify(comp, expectedOutput: "(R, R2)"); } [Fact] public void RecordWithConstraints_ConstraintError() { var src = @" record struct R<T>(T P) where T : class; record struct R2<T>(T P) where T : class { } public class C { public static void Main() { _ = new R<int>(1); _ = new R2<int>(2); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R<T>' // _ = new R<int>(1); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R<T>", "T", "int").WithLocation(9, 19), // (10,20): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R2<T>' // _ = new R2<int>(2); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R2<T>", "T", "int").WithLocation(10, 20) ); } [Fact] public void CyclicBases4() { var text = @" record struct A<T> : B<A<T>> { } record struct B<T> : A<B<T>> { A<T> F() { return null; } } "; var comp = CreateCompilation(text); comp.GetDeclarationDiagnostics().Verify( // (3,22): error CS0527: Type 'A<B<T>>' in interface list is not an interface // record struct B<T> : A<B<T>> Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "A<B<T>>").WithArguments("A<B<T>>").WithLocation(3, 22), // (2,22): error CS0527: Type 'B<A<T>>' in interface list is not an interface // record struct A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "B<A<T>>").WithArguments("B<A<T>>").WithLocation(2, 22) ); } [Fact] public void PartialClassWithDifferentTupleNamesInImplementedInterfaces() { var source = @" public interface I<T> { } public partial record C1 : I<(int a, int b)> { } public partial record C1 : I<(int notA, int notB)> { } public partial record C2 : I<(int a, int b)> { } public partial record C2 : I<(int, int)> { } public partial record C3 : I<(int a, int b)> { } public partial record C3 : I<(int a, int b)> { } public partial record C4 : I<(int a, int b)> { } public partial record C4 : I<(int b, int a)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,23): error CS8140: 'I<(int notA, int notB)>' is already listed in the interface list on type 'C1' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C1 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I<(int notA, int notB)>", "I<(int a, int b)>", "C1").WithLocation(3, 23), // (6,23): error CS8140: 'I<(int, int)>' is already listed in the interface list on type 'C2' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C2 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C2").WithArguments("I<(int, int)>", "I<(int a, int b)>", "C2").WithLocation(6, 23), // (12,23): error CS8140: 'I<(int b, int a)>' is already listed in the interface list on type 'C4' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C4 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C4").WithArguments("I<(int b, int a)>", "I<(int a, int b)>", "C4").WithLocation(12, 23) ); } [Fact] public void CS0267ERR_PartialMisplaced() { var test = @" partial public record struct C // CS0267 { } "; CreateCompilation(test).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial public record struct C // CS0267 Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1) ); } [Fact] public void SealedStaticRecord() { var source = @" sealed static record struct R; "; CreateCompilation(source).VerifyDiagnostics( // (2,29): error CS0106: The modifier 'sealed' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("sealed").WithLocation(2, 29), // (2,29): error CS0106: The modifier 'static' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 29) ); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" record struct C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(5, 25), // (4,41): error CS0106: The modifier 'abstract' is not valid for this item // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_BadMemberFlag, "E").WithArguments("abstract").WithLocation(4, 41) ); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" public record struct iii { ~iiii(){} } "; CreateCompilation(test).VerifyDiagnostics( // (4,6): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(4, 6), // (4,6): error CS0575: Only class types can contain destructors // ~iiii(){} Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "iiii").WithArguments("iii.~iii()").WithLocation(4, 6) ); } [Fact] public void StaticRecordWithConstructorAndDestructor() { var text = @" static record struct R(int I) { public R() : this(0) { } ~R() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,22): error CS0106: The modifier 'static' is not valid for this item // static record struct R(int I) Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22), // (5,6): error CS0575: Only class types can contain destructors // ~R() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "R").WithArguments("R.~R()").WithLocation(5, 6) ); } [Fact] public void RecordWithPartialMethodExplicitImplementation() { var source = @"record struct R { partial void M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,18): error CS0751: A partial method must be declared within a partial type // partial void M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 18) ); } [Fact] public void RecordWithPartialMethodRequiringBody() { var source = @"partial record struct R { public partial int M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,24): error CS8795: Partial method 'R.M()' must have an implementation part because it has accessibility modifiers. // public partial int M(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M").WithArguments("R.M()").WithLocation(3, 24) ); } [Fact] public void CanDeclareIteratorInRecord() { var source = @" using System.Collections.Generic; foreach(var i in new X(42).GetItems()) { System.Console.Write(i); } public record struct X(int a) { public IEnumerable<int> GetItems() { yield return a; yield return a + 1; } }"; var comp = CreateCompilation(source).VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "4243"); } [Fact] public void ParameterlessConstructor() { var src = @" System.Console.Write(new C().Property); record struct C() { public int Property { get; set; } = 42; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void XmlDoc() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record struct C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] public void XmlDoc_Cref() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for <see cref=""I1""/></param> public record struct C(int I1) { /// <summary>Summary</summary> /// <param name=""x"">Description for <see cref=""x""/></param> public void M(int x) { } } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,52): warning CS1574: XML comment has cref attribute 'x' that could not be resolved // /// <param name="x">Description for <see cref="x"/></param> Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x").WithLocation(7, 52) ); var tree = comp.SyntaxTrees.Single(); var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>(); var cref = docComments.First().DescendantNodes().OfType<XmlCrefAttributeSyntax>().First().Cref; Assert.Equal("I1", cref.ToString()); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal(SymbolKind.Property, model.GetSymbolInfo(cref).Symbol!.Kind); } [Fact] public void Deconstruct_Simple() { var source = @"using System; record struct B(int X, int Y) { public static void Main() { M(new B(1, 2)); } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); var deconstruct = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("B.Deconstruct"); Assert.Equal(2, deconstruct.ParameterCount); Assert.Equal(RefKind.Out, deconstruct.Parameters[0].RefKind); Assert.Equal("X", deconstruct.Parameters[0].Name); Assert.Equal(RefKind.Out, deconstruct.Parameters[1].RefKind); Assert.Equal("Y", deconstruct.Parameters[1].Name); Assert.True(deconstruct.ReturnsVoid); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsStatic); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); } [Fact] public void Deconstruct_PositionalAndNominalProperty() { var source = @"using System; record struct B(int X) { public int Y { get; init; } = 0; public static void Main() { M(new B(1)); } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "readonly void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Nested() { var source = @"using System; record struct B(int X, int Y); record struct C(B B, int Z) { public static void Main() { M(new C(new B(1, 2), 3)); } static void M(C c) { switch (c) { case C(B(int x, int y), int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly B C.B.get"" IL_0007: stobj ""B"" IL_000c: ldarg.2 IL_000d: ldarg.0 IL_000e: call ""readonly int C.Z.get"" IL_0013: stind.i4 IL_0014: ret }"); } [Fact] public void Deconstruct_PropertyCollision() { var source = @"using System; record struct B(int X, int Y) { public int X => 3; static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "32"); verifier.VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_01() { var source = @" record struct B(int X, int Y) { public int X() => 3; static void M(B b) { switch (b) { case B(int x, int y): break; } } static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'B' already contains a definition for 'X' // public int X() => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("B", "X").WithLocation(4, 16) ); Assert.Equal( "readonly void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_FieldCollision() { var source = @" using System; record struct C(int X) { int X = 0; static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(0)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 21), // (6,9): warning CS0414: The field 'C.X' is assigned but its value is never used // int X = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "X").WithArguments("C.X").WithLocation(6, 9)); Assert.Equal( "readonly void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty() { var source = @" record struct C { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Conversion_02() { var source = @" #nullable enable using System; record struct C(string? X, string Y) { public string X { get; init; } = null!; public string? Y { get; init; } = string.Empty; static void M(C c) { switch (c) { case C(var x, string y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(""a"", ""b"")); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,25): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 25), // (5,35): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 35) ); Assert.Equal( "readonly void C.Deconstruct(out System.String? X, out System.String Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty_WithParameterList() { var source = @" record struct C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); AssertEx.Equal(new[] { "C..ctor()", "void C.M(C c)", "void C.Main()", "readonly System.String C.ToString()", "readonly System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "readonly System.Int32 C.GetHashCode()", "readonly System.Boolean C.Equals(System.Object obj)", "readonly System.Boolean C.Equals(C other)" }, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings()); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_01() { var source = @"using System; record struct C(int I) { public void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C(42)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordDeconstruct>("A.Deconstruct"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void Deconstruct_WihtNonReadOnlyGetter_GeneratedAsNonReadOnly() { var src = @" record struct A(int I, string S) { public int I { get => 0; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record struct A(int I, string S) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 21)); var method = comp.GetMember<SynthesizedRecordDeconstruct>("A.Deconstruct"); Assert.False(method.IsDeclaredReadOnly); } [Fact] public void Deconstruct_UserDefined() { var source = @"using System; record struct B(int X, int Y) { public void Deconstruct(out int X, out int Y) { X = this.X + 1; Y = this.Y + 2; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(0, 0)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_02() { var source = @"using System; record struct B(int X) { public int Deconstruct(out int a) => throw null; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS8874: Record member 'B.Deconstruct(out int)' must return 'void'. // public int Deconstruct(out int a) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Deconstruct").WithArguments("B.Deconstruct(out int)", "void").WithLocation(5, 16), // (11,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'B', with 1 out parameters and a void return type. // case B(int x): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int x)").WithArguments("B", "1").WithLocation(11, 19)); Assert.Equal("System.Int32 B.Deconstruct(out System.Int32 a)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void Deconstruct_UserDefined_Accessibility_07(string accessibility) { var source = $@" record struct A(int X) {{ { accessibility } void Deconstruct(out int a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,11): error CS8873: Record member 'A.Deconstruct(out int)' must be public. // void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void Deconstruct_UserDefined_Static_08() { var source = @" record struct A(int X) { public static void Deconstruct(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS8877: Record member 'A.Deconstruct(out int)' may not be static. // public static void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 24) ); } [Fact] public void OutVarInPositionalParameterDefaultValue() { var source = @" record struct A(int X = A.M(out int a) + a) { public static int M(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,25): error CS1736: Default parameter value for 'X' must be a compile-time constant // record struct A(int X = A.M(out int a) + a) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "A.M(out int a) + a").WithArguments("X").WithLocation(2, 25) ); } [Fact] public void FieldConsideredUnassignedIfInitializationViaProperty() { var source = @" record struct Pos(int X) { private int x; public int X { get { return x; } set { x = value; } } = X; } record struct Pos2(int X) { private int x = X; // value isn't validated by setter public int X { get { return x; } set { x = value; } } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0171: Field 'Pos.x' must be fully assigned before control is returned to the caller // record struct Pos(int X) Diagnostic(ErrorCode.ERR_UnassignedThis, "Pos").WithArguments("Pos.x").WithLocation(2, 15), // (5,16): error CS8050: Only auto-implemented properties can have initializers. // public int X { get { return x; } set { x = value; } } = X; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "X").WithArguments("Pos.X").WithLocation(5, 16) ); } [Fact] public void IEquatableT_01() { var source = @"record struct A<T>; class Program { static void F<T>(System.IEquatable<T> t) { } static void M<T>() { F(new A<T>()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( ); } [Fact] public void IEquatableT_02() { var source = @"using System; record struct A; record struct B<T>; class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "TrueTrue").VerifyDiagnostics(); } [Fact] public void IEquatableT_02_ImplicitImplementation() { var source = @"using System; record struct A { public bool Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { public bool Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics( // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17), // (12,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B<T> other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(12, 17) ); } [Fact] public void IEquatableT_02_ExplicitImplementation() { var source = @"using System; record struct A { bool IEquatable<A>.Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { bool IEquatable<B<T>>.Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics(); } [Fact] public void IEquatableT_03() { var source = @" record struct A<T> : System.IEquatable<A<T>>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_MissingIEquatable() { var source = @" record struct A<T>; "; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_IEquatable_T); comp.VerifyEmitDiagnostics( // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void RecordEquals_01() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); record struct B { public bool Equals(B other) { System.Console.WriteLine(""B.Equals(B)""); return false; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 17) ); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False "); } [Fact] public void RecordEquals_01_NoInParameters() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(in a2)); record struct B; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,39): error CS1615: Argument 1 may not be passed with the 'in' keyword // System.Console.WriteLine(a1.Equals(in a2)); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "a2").WithArguments("1", "in").WithLocation(4, 39) ); } [Theory] [InlineData("protected")] [InlineData("private protected")] [InlineData("internal protected")] public void RecordEquals_10(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,29): error CS0666: 'A.Equals(A)': new protected member declared in struct // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): error CS8873: Record member 'A.Equals(A)' must be public. // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // internal protected bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void RecordEquals_11(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,11): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void RecordEquals_12() { var source = @" A a1 = new A(); A a2 = new A(); System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); record struct A { public bool Equals(B other) => throw null; } class B { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""readonly bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(A other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); var objectEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordObjEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(System.Object obj)", objectEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, objectEquals.DeclaredAccessibility); Assert.False(objectEquals.IsAbstract); Assert.False(objectEquals.IsVirtual); Assert.True(objectEquals.IsOverride); Assert.False(objectEquals.IsSealed); Assert.True(objectEquals.IsImplicitlyDeclared); MethodSymbol gethashCode = comp.GetMembers("A." + WellKnownMemberNames.ObjectGetHashCode).OfType<SynthesizedRecordGetHashCode>().Single(); Assert.Equal("readonly System.Int32 A.GetHashCode()", gethashCode.ToTestDisplayString()); Assert.Equal(Accessibility.Public, gethashCode.DeclaredAccessibility); Assert.False(gethashCode.IsStatic); Assert.False(gethashCode.IsAbstract); Assert.False(gethashCode.IsVirtual); Assert.True(gethashCode.IsOverride); Assert.False(gethashCode.IsSealed); Assert.True(gethashCode.IsImplicitlyDeclared); } [Fact] public void RecordEquals_13() { var source = @" record struct A { public int Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,16): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public int Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 16), // (4,16): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public int Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 16) ); } [Fact] public void RecordEquals_14() { var source = @" record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (4,12): error CS0518: Predefined type 'System.Boolean' is not defined or imported // public bool Equals(A other) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 12), // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17) ); } [Fact] public void RecordEquals_19() { var source = @" record struct A { public static bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void RecordEquals_RecordEqualsInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool Equals(A x) => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) ); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(A other)", recordEquals.ToTestDisplayString()); } [Fact] public void RecordEquals_FourFields() { var source = @" A a1 = new A(1, ""hello""); System.Console.Write(a1.Equals(a1)); System.Console.Write(a1.Equals((object)a1)); System.Console.Write("" - ""); A a2 = new A(1, ""hello"") { fieldI = 100 }; System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); System.Console.Write(a2.Equals(a1)); System.Console.Write(a2.Equals((object)a1)); System.Console.Write("" - ""); A a3 = new A(1, ""world""); System.Console.Write(a1.Equals(a3)); System.Console.Write(a1.Equals((object)a3)); System.Console.Write(a3.Equals(a1)); System.Console.Write(a3.Equals((object)a1)); record struct A(int I, string S) { public int fieldI = 42; public string fieldS = ""hello""; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue - FalseFalseFalseFalse - FalseFalseFalseFalse"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 97 (0x61) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int A.<I>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_005f IL_0018: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""string A.<S>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""string A.<S>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_002e: brfalse.s IL_005f IL_0030: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0035: ldarg.0 IL_0036: ldfld ""int A.fieldI"" IL_003b: ldarg.1 IL_003c: ldfld ""int A.fieldI"" IL_0041: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0046: brfalse.s IL_005f IL_0048: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_004d: ldarg.0 IL_004e: ldfld ""string A.fieldS"" IL_0053: ldarg.1 IL_0054: ldfld ""string A.fieldS"" IL_0059: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_005e: ret IL_005f: ldc.i4.0 IL_0060: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""readonly bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 86 (0x56) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""string A.<S>k__BackingField"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0026: add IL_0027: ldc.i4 0xa5555529 IL_002c: mul IL_002d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0032: ldarg.0 IL_0033: ldfld ""int A.fieldI"" IL_0038: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_003d: add IL_003e: ldc.i4 0xa5555529 IL_0043: mul IL_0044: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_0049: ldarg.0 IL_004a: ldfld ""string A.fieldS"" IL_004f: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0054: add IL_0055: ret }"); } [Fact] public void RecordEquals_StaticField() { var source = @" record struct A { public static int field = 42; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void RecordEquals_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.True(recordEquals.IsDeclaredReadOnly); } [Fact] public void ObjectEquals_06() { var source = @" record struct A { public static new bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,28): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public static new bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(4, 28) ); } [Fact] public void ObjectEquals_UserDefined() { var source = @" record struct A { public override bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,26): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public override bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(4, 26) ); } [Fact] public void ObjectEquals_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var objectEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordObjEquals>().Single(); Assert.True(objectEquals.IsDeclaredReadOnly); } [Fact] public void GetHashCode_UserDefined() { var source = @" System.Console.Write(new A().GetHashCode()); record struct A { public override int GetHashCode() => 42; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void GetHashCode_GetHashCodeInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public virtual int GetHashCode() => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (2,22): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public record struct A; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "A").WithArguments("A.GetHashCode()").WithLocation(2, 22) ); } [Fact] public void GetHashCode_MissingEqualityComparer_EmptyRecord() { var src = @" public record struct A; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics(); } [Fact] public void GetHashCode_MissingEqualityComparer_NonEmptyRecord() { var src = @" public record struct A(int I); "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1) ); } [Fact] public void GetHashCode_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordGetHashCode>("A.GetHashCode"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void GetHashCodeIsDefinedButEqualsIsNot() { var src = @" public record struct C { public object Data; public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void EqualsIsDefinedButGetHashCodeIsNot() { var src = @" public record struct C { public object Data; public bool Equals(C c) { return false; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) { return false; } Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(5, 17)); } [Fact] public void EqualityOperators_01() { var source = @" record struct A(int X) { public bool Equals(ref A other) => throw null; static void Main() { Test(default, default); Test(default, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); var a = new A(11); Test(a, a); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False True True False False True True False False False False True True True True False False ").VerifyDiagnostics(); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A left, A right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A left, A right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: ldarg.1 IL_0003: call ""readonly bool A.Equals(A)"" IL_0008: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_03() { var source = @" record struct A { public static bool operator==(A r1, A r2) => throw null; public static bool operator==(A r1, string r2) => throw null; public static bool operator!=(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool operator==(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "==").WithArguments("op_Equality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_04() { var source = @" record struct A { public static bool operator!=(A r1, A r2) => throw null; public static bool operator!=(string r1, A r2) => throw null; public static bool operator==(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool operator!=(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "!=").WithArguments("op_Inequality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_05() { var source = @" record struct A { public static bool op_Equality(A r1, A r2) => throw null; public static bool op_Equality(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool op_Equality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Equality").WithArguments("op_Equality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_06() { var source = @" record struct A { public static bool op_Inequality(A r1, A r2) => throw null; public static bool op_Inequality(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool op_Inequality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Inequality").WithArguments("op_Inequality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_07() { var source = @" record struct A { public static bool Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A other) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Theory] [CombinatorialData] public void EqualityOperators_09(bool useImageReference) { var source1 = @" public record struct A(int X); "; var comp1 = CreateCompilation(source1); var source2 = @" class Program { static void Main() { Test(default, default); Test(default, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; CompileAndVerify(source2, references: new[] { useImageReference ? comp1.EmitToImageReference() : comp1.ToMetadataReference() }, expectedOutput: @" True True False False True True False False True True False False False False True True ").VerifyDiagnostics(); } [Fact] public void GetSimpleNonTypeMembers_DirectApiCheck() { var src = @" public record struct RecordB(); "; var comp = CreateCompilation(src); var b = comp.GlobalNamespace.GetTypeMember("RecordB"); AssertEx.SetEqual(new[] { "System.Boolean RecordB.op_Equality(RecordB left, RecordB right)" }, b.GetSimpleNonTypeMembers("op_Equality").ToTestDisplayStrings()); } [Fact] public void ToString_NestedRecord() { var src = @" var c1 = new Outer.C1(42); System.Console.Write(c1.ToString()); public class Outer { public record struct C1(int I1); } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }"); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }"); compRelease.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_Empty() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: call ""readonly bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilder() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Text_StringBuilder); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record struct C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 15) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderCtor() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__ctor); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderAppendString() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString() { var src = @" record struct C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_RecordWithIndexer() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record struct C1(int I1) { private int field = 44; public int this[int i] => 0; public int PropertyWithoutGetter { set { } } public int P2 { get => 43; } public event System.Action a = null; private int field1 = 100; internal int field2 = 100; private int Property1 { get; set; } = 100; internal int Property2 { get; set; } = 100; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43 }"); comp.VerifyEmitDiagnostics( // (7,17): warning CS0414: The field 'C1.field' is assigned but its value is never used // private int field = 44; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C1.field").WithLocation(7, 17), // (11,32): warning CS0414: The field 'C1.a' is assigned but its value is never used // public event System.Action a = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("C1.a").WithLocation(11, 32), // (13,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used // private int field1 = 100; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1").WithArguments("C1.field1").WithLocation(13, 17) ); } [Fact] public void ToString_PrivateGetter() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public int P1 { private get => 43; set => throw null; } } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }"); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_OneField_ValueType() { var src = @" var c1 = new C1() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1 { public int field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldflda ""int C1.field"" IL_0013: constrained. ""int"" IL_0019: callvirt ""string object.ToString()"" IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0023: pop IL_0024: ldc.i4.1 IL_0025: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ConstrainedValueType() { var src = @" var c1 = new C1<int>() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1<T> where T : struct { public T field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 41 (0x29) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldfld ""T C1<T>.field"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldc.i4.1 IL_0028: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ReferenceType() { var src = @" var c1 = new C1() { field = ""hello"" }; System.Console.Write(c1.ToString()); record struct C1 { public string field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldfld ""string C1.field"" IL_0013: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0018: pop IL_0019: ldc.i4.1 IL_001a: ret } "); } [Fact] public void ToString_TopLevelRecord_TwoFields_ReferenceType() { var src = @" var c1 = new C1(42) { field1 = ""hi"", field2 = null }; System.Console.Write(c1.ToString()); record struct C1(int I) { public string field1 = null; public string field2 = null; private string field3 = null; internal string field4 = null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,20): warning CS0414: The field 'C1.field3' is assigned but its value is never used // private string field3 = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field3").WithArguments("C1.field3").WithLocation(10, 20) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42, field1 = hi, field2 = }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 91 (0x5b) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""readonly int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldarg.1 IL_0028: ldstr "", field1 = "" IL_002d: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0032: pop IL_0033: ldarg.1 IL_0034: ldarg.0 IL_0035: ldfld ""string C1.field1"" IL_003a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_003f: pop IL_0040: ldarg.1 IL_0041: ldstr "", field2 = "" IL_0046: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_004b: pop IL_004c: ldarg.1 IL_004d: ldarg.0 IL_004e: ldfld ""string C1.field2"" IL_0053: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0058: pop IL_0059: ldc.i4.1 IL_005a: ret } "); } [Fact] public void ToString_TopLevelRecord_Readonly() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); readonly record struct C1(int I); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 41 (0x29) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldc.i4.1 IL_0028: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: call ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public override string ToString() => ""RAN""; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("readonly System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString()); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_New() { var src = @" record struct C1 { public new string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS8869: 'C1.ToString()' does not override expected method from 'object'. // public new string ToString() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "ToString").WithArguments("C1.ToString()").WithLocation(4, 23) ); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_Sealed() { var src = @" record struct C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,35): error CS0106: The modifier 'sealed' is not valid for this item // public sealed override string ToString() => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("sealed").WithLocation(4, 35) ); } [Fact] public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder() { var src = @" #nullable enable record struct C1 { private bool PrintMembers(System.Text.StringBuilder? builder) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_ErrorReturnType() { var src = @" record struct C1 { private Error PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,13): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // private Error PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 13) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongReturnType() { var src = @" record struct C1 { private int PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,17): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'. // private int PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 17) ); } [Fact] public void ToString_UserDefinedPrintMembers() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1 { private bool PrintMembers(System.Text.StringBuilder builder) { builder.Append(""RAN""); return true; } public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { RAN } - RAN"); } [Fact] public void ToString_CallingSynthesizedPrintMembers() { var src = @" var c1 = new C1(1, 2, 3); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1(int I, int I2, int I3) { public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { I = 1, I2 = 2, I3 = 3 } - I = 1, I2 = 2, I3 = 3"); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility() { var src = @" var c = new C1(); System.Console.Write(c.ToString()); record struct C1 { internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (7,19): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private. // internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(7, 19) ); } [Fact] public void ToString_UserDefinedPrintMembers_Static() { var src = @" record struct C1 { static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8877: Record member 'C1.PrintMembers(StringBuilder)' may not be static. // static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordToString>("A.ToString"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void ToString_WihtNonReadOnlyGetter_GeneratedAsNonReadOnly() { var src = @" record struct A(int I, string S) { public double T => 0.1; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordToString>("A.ToString"); Assert.False(method.IsDeclaredReadOnly); } [Fact] public void AmbigCtor_WithPropertyInitializer() { // Scenario causes ambiguous ctor for record class, but not record struct var src = @" record struct R(R X) { public R X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,14): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // public R X { get; init; } = X; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(4, 14) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var parameterSyntax = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); var parameter = model.GetDeclaredSymbol(parameterSyntax)!; Assert.Equal("R X", parameter.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, parameter.Kind); Assert.Equal("R..ctor(R X)", parameter.ContainingSymbol.ToTestDisplayString()); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); var initializer = model.GetSymbolInfo(initializerSyntax.Value).Symbol!; Assert.Equal("R X", initializer.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, initializer.Kind); Assert.Equal("R..ctor(R X)", initializer.ContainingSymbol.ToTestDisplayString()); var src2 = @" record struct R(R X); "; var comp2 = CreateCompilation(src2); comp2.VerifyEmitDiagnostics( // (2,19): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // record struct R(R X); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(2, 19) ); } [Fact] public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer() { var src = @" record struct R(int I) { public int I { get; init; } = M(out int i); static int M(out int i) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 21) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var outVarSyntax = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Single(); var outVar = model.GetDeclaredSymbol(outVarSyntax)!; Assert.Equal("System.Int32 i", outVar.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, outVar.Kind); Assert.Equal("System.Int32 R.<I>k__BackingField", outVar.ContainingSymbol.ToTestDisplayString()); } [Fact] public void AnalyzerActions_01() { // Test RegisterSyntaxNodeAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } interface I1 {} class Attr1 : System.Attribute {} "; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCountRecordStructDeclarationA); Assert.Equal(1, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCountConstructorDeclaration); Assert.Equal(1, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount0; public int FireCountRecordStructDeclarationA; public int FireCountRecordStructDeclarationACtor; public int FireCount3; public int FireCountSimpleBaseTypeI1onA; public int FireCount5; public int FireCountParameterListAPrimaryCtor; public int FireCount7; public int FireCountConstructorDeclaration; public int FireCountStringParameterList; public int FireCountThisConstructorInitializer; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); } protected void Handle1(SyntaxNodeAnalysisContext context) { var literal = (LiteralExpressionSyntax)context.Node; switch (literal.ToString()) { case "0": Interlocked.Increment(ref FireCount0); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "3": Interlocked.Increment(ref FireCount7); Assert.Equal("System.Int32 A.M()", context.ContainingSymbol.ToTestDisplayString()); break; case "4": Interlocked.Increment(ref FireCount12); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(literal.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle2(SyntaxNodeAnalysisContext context) { var equalsValue = (EqualsValueClauseSyntax)context.Node; switch (equalsValue.ToString()) { case "= 0": Interlocked.Increment(ref FireCount3); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(equalsValue.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle3(SyntaxNodeAnalysisContext context) { var initializer = (ConstructorInitializerSyntax)context.Node; switch (initializer.ToString()) { case ": this(4)": Interlocked.Increment(ref FireCountThisConstructorInitializer); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(initializer.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle4(SyntaxNodeAnalysisContext context) { Interlocked.Increment(ref FireCountConstructorDeclaration); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); } protected void Fail(SyntaxNodeAnalysisContext context) { Assert.True(false); } protected void Handle6(SyntaxNodeAnalysisContext context) { var record = (RecordDeclarationSyntax)context.Node; Assert.Equal(SyntaxKind.RecordStructDeclaration, record.Kind()); switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCountRecordStructDeclarationA); break; case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCountRecordStructDeclarationACtor); break; default: Assert.True(false); break; } Assert.Same(record.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle7(SyntaxNodeAnalysisContext context) { var identifier = (IdentifierNameSyntax)context.Node; switch (identifier.Identifier.ValueText) { case "Attr1": Interlocked.Increment(ref FireCount5); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; } } protected void Handle8(SyntaxNodeAnalysisContext context) { var baseType = (SimpleBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "I1": switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCountSimpleBaseTypeI1onA); break; default: Assert.True(false); break; } break; case "System.Attribute": break; default: Assert.True(false); break; } } protected void Handle9(SyntaxNodeAnalysisContext context) { var parameterList = (ParameterListSyntax)context.Node; switch (parameterList.ToString()) { case "([Attr1]int X = 0)": Interlocked.Increment(ref FireCountParameterListAPrimaryCtor); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "(string S)": Interlocked.Increment(ref FireCountStringParameterList); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; case "()": break; default: Assert.True(false); break; } } protected void Handle10(SyntaxNodeAnalysisContext context) { var argumentList = (ArgumentListSyntax)context.Node; switch (argumentList.ToString()) { case "(4)": Interlocked.Increment(ref FireCount11); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { // Test RegisterSymbolAction var text1 = @" record struct A(int X = 0) {} record struct C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); context.RegisterSymbolAction(Handle, SymbolKind.Property); context.RegisterSymbolAction(Handle, SymbolKind.Parameter); context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "System.Int32 A.X { get; set; }": Interlocked.Increment(ref FireCount2); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount6); break; case "C": Interlocked.Increment(ref FireCount7); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { // Test RegisterSymbolStartAction var text1 = @" readonly record struct A(int X = 0) {} readonly record struct C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(0, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle1, SymbolKind.Property); context.RegisterSymbolStartAction(Handle1, SymbolKind.Parameter); context.RegisterSymbolStartAction(Handle1, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle2); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle3); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); context.RegisterSymbolEndAction(Handle4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount9); Assert.Equal(0, FireCount1); Assert.Equal(0, FireCount2); Assert.Equal(0, FireCount6); Assert.Equal(0, FireCount7); context.RegisterSymbolEndAction(Handle5); break; case "C": Interlocked.Increment(ref FireCount10); Assert.Equal(0, FireCount4); Assert.Equal(0, FireCount8); context.RegisterSymbolEndAction(Handle6); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { Assert.Equal("A..ctor([System.Int32 X = 0])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("System.Int32 A.X { get; init; }", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("C..ctor([System.Int32 Z = 4])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal("A", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); Assert.Equal(1, FireCount1); Assert.Equal(1, FireCount2); Assert.Equal(1, FireCount6); Assert.Equal(1, FireCount7); } private void Handle6(SymbolAnalysisContext context) { Assert.Equal("C", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); Assert.Equal(1, FireCount4); Assert.Equal(1, FireCount8); } } [Fact] public void AnalyzerActions_04() { // Test RegisterOperationAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} interface I1 {} "; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount14); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount6; public int FireCount7; public int FireCount14; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(HandleConstructorBody, OperationKind.ConstructorBody); context.RegisterOperationAction(HandleInvocation, OperationKind.Invocation); context.RegisterOperationAction(HandleLiteral, OperationKind.Literal); context.RegisterOperationAction(HandleParameterInitializer, OperationKind.ParameterInitializer); context.RegisterOperationAction(Fail, OperationKind.PropertyInitializer); context.RegisterOperationAction(Fail, OperationKind.FieldInitializer); } protected void HandleConstructorBody(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @""); break; default: Assert.True(false); break; } } protected void HandleInvocation(OperationAnalysisContext context) { Assert.True(false); } protected void HandleLiteral(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "100": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); break; case "0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); break; default: Assert.True(false); break; } } protected void HandleParameterInitializer(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "= 0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount14); break; default: Assert.True(false); break; } } protected void Fail(OperationAnalysisContext context) { Assert.True(false); } } [Fact] public void AnalyzerActions_05() { // Test RegisterOperationBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} interface I1 {} "; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { // Test RegisterCodeBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 { int M() => 3; } interface I1 {} "; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_08() { // Test RegisterCodeBlockStartAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } interface I1 {} "; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(1, analyzer.FireCount500); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationA); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(0, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(0, analyzer.FireCountConstructorDeclaration); Assert.Equal(0, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount4000); Assert.Equal(1, analyzer.FireCount5000); } private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer { public int FireCount100; public int FireCount400; public int FireCount500; public int FireCount1000; public int FireCount4000; public int FireCount5000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount100); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount400); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount500); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); context.RegisterCodeBlockEndAction(Handle11); } private void Handle11(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1000); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4000); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount5000); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_09() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Property); context.RegisterSymbolAction(Handle3, SymbolKind.Parameter); } private void Handle1(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount5); break; case "System.Int32 B.Y { get; init; }": Interlocked.Increment(ref FireCount6); break; default: Assert.True(false); break; } } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount7); break; case "[System.Int32 Y = 1]": Interlocked.Increment(ref FireCount8); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount9); break; default: Assert.True(false); break; } } } [Fact] public void WithExprOnStruct_LangVersion() { var src = @" var b = new B() { X = 1 }; var b2 = b.M(); System.Console.Write(b2.X); System.Console.Write("" ""); System.Console.Write(b.X); public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42 }; }/*</bind>*/ }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,16): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater. // return this with { X = 42 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "this with { X = 42 }").WithArguments("with on structs", "10.0").WithLocation(13, 16) ); comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 1"); verifier.VerifyIL("B.M", @" { // Code size 18 (0x12) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: ldobj ""B"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: ldc.i4.s 42 IL_000b: call ""void B.X.set"" IL_0010: ldloc.0 IL_0011: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("B", type.Type.ToTestDisplayString()); var operation = model.GetOperation(with); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: B) (Syntax: 'this with { X = 42 }') Operand: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: B) (Syntax: '{ X = 42 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_DuplicateInitialization() { var src = @" public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42, X = 43 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (8,36): error CS1912: Duplicate initialization of member 'X' // return this with { X = 42, X = 43 }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'X = 43') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 43) (Syntax: '43') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NestedInitializer() { var src = @" public struct C { public int Y { get; set; } } public struct B { public C X { get; set; } public B M() /*<bind>*/{ return this with { X = { Y = 1 } }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (12,32): error CS1525: Invalid expression term '{' // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(12, 32), // (12,32): error CS1513: } expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(12, 32), // (12,32): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(12, 32), // (12,34): error CS0103: The name 'Y' does not exist in the current context // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y").WithLocation(12, 34), // (12,34): warning CS0162: Unreachable code detected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.WRN_UnreachableCode, "Y").WithLocation(12, 34), // (12,40): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(12, 40), // (12,43): error CS1597: Semicolon after method or accessor block is not valid // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(12, 43), // (14,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(14, 1) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'X = ') Left: IPropertyReferenceOperation: C B.X { get; set; } (OperationKind.PropertyReference, Type: C) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Return) Block[B3] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Y = 1 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Y = 1') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Y') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NonAssignmentExpression() { var src = @" public struct B { public int X { get; set; } public B M(int i, int j) /*<bind>*/{ return this with { i, j++, M2(), X = 2}; }/*</bind>*/ static int M2() => 0; }"; var expectedDiagnostics = new[] { // (8,28): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(8, 28), // (8,31): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(8, 31), // (8,36): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 B.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void ObjectCreationInitializer_ControlFlow_WithCoalescingExpressionForValue() { var src = @" public struct B { public string X; public void M(string hello) /*<bind>*/{ var x = new B() { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [B x] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Value: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B) (Syntax: 'new B() { X ... ty(hello) }') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics); } [Fact] public void WithExprOnStruct_ControlFlow_WithCoalescingExpressionForValue() { var src = @" var b = new B() { X = string.Empty }; var b2 = b.M(""hello""); System.Console.Write(b2.X); public struct B { public string X; public B M(string hello) /*<bind>*/{ return Identity(this) with { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(this)') Value: IInvocationOperation ( B B.Identity<B>(B t)) (OperationKind.Invocation, Type: B) (Syntax: 'Identity(this)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (0) Next (Return) Block[B7] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_OnParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public struct B { public int X { get; set; } public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnThis() { var src = @" record struct C { public int X { get; set; } C(string ignored) { _ = this with { X = 42 }; // 1 this = default; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0188: The 'this' object cannot be used before all of its fields have been assigned // _ = this with { X = 42 }; // 1 Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this").WithLocation(8, 13) ); } [Fact] public void WithExprOnStruct_OnTStructParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public interface I { int X { get; set; } } public struct B : I { public int X { get; set; } public static T M<T>(T b) where T : struct, I { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M<T>(T)", @" { // Code size 19 (0x13) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: constrained. ""T"" IL_000c: callvirt ""void I.X.set"" IL_0011: ldloc.0 IL_0012: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("T", type.Type.ToTestDisplayString()); } [Fact] public void WithExprOnStruct_OnRecordStructParameter() { var src = @" var b = new B(1); var b2 = B.M(b); System.Console.Write(b2.X); public record struct B(int X) { public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnRecordStructParameter_Readonly() { var src = @" var b = new B(1, 2); var b2 = B.M(b); System.Console.Write(b2.X); System.Console.Write(b2.Y); public readonly record struct B(int X, int Y) { public static B M(B b) { return b with { X = 42, Y = 43 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("B.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.init"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: call ""void B.Y.init"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple() { var src = @" class C { static void Main() { var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); } static (int, int) M((int, int) b) { return b with { Item1 = 42, Item2 = 43 }; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_WithNames() { var src = @" var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); static (int, int) M((int X, int Y) b) { return b with { X = 42, Y = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int>)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_LongTuple() { var src = @" var b = (1, 2, 3, 4, 5, 6, 7, 8); var b2 = M(b); System.Console.Write(b2.Item7); System.Console.Write(b2.Item8); static (int, int, int, int, int, int, int, int) M((int, int, int, int, int, int, int, int) b) { return b with { Item7 = 42, Item8 = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>)", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item7"" IL_000b: ldloca.s V_0 IL_000d: ldflda ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest"" IL_0012: ldc.i4.s 43 IL_0014: stfld ""int System.ValueTuple<int>.Item1"" IL_0019: ldloc.0 IL_001a: ret }"); } [Fact] public void WithExprOnStruct_OnReadonlyField() { var src = @" var b = new B { X = 1 }; // 1 public struct B { public readonly int X; public B M() { return this with { X = 42 }; // 2 } public static B M2(B b) { return b with { X = 42 }; // 3 } public B(int i) { this = default; _ = this with { X = 42 }; // 4 } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // var b = new B { X = 1 }; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(2, 17), // (9,28): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return this with { X = 42 }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(9, 28), // (13,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return b with { X = 42 }; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(13, 25), // (18,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = this with { X = 42 }; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(18, 25) ); } [Fact] public void WithExprOnStruct_OnEnum() { var src = @" public enum E { } class C { static E M(E e) { return e with { }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void WithExprOnStruct_OnPointer() { var src = @" unsafe class C { static int* M(int* i) { return i with { }; } }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (6,16): error CS8858: The receiver type 'int*' is not a valid record type and is not a struct type. // return i with { }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("int*").WithLocation(6, 16) ); } [Fact] public void WithExprOnStruct_OnInterface() { var src = @" public interface I { int X { get; set; } } class C { static I M(I i) { return i with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,16): error CS8858: The receiver type 'I' is not a valid record type and is not a value type. // return i with { X = 42 }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("I").WithLocation(10, 16) ); } [Fact] public void WithExprOnStruct_OnRefStruct() { // Similar to test RefLikeObjInitializers but with `with` expressions var text = @" using System; class Program { static S2 Test1() { S1 outer = default; S1 inner = stackalloc int[1]; // error return new S2() with { Field1 = outer, Field2 = inner }; } static S2 Test2() { S1 outer = default; S1 inner = stackalloc int[1]; S2 result; // error result = new S2() with { Field1 = inner, Field2 = outer }; return result; } static S2 Test3() { S1 outer = default; S1 inner = stackalloc int[1]; return new S2() with { Field1 = outer, Field2 = outer }; } public ref struct S1 { public static implicit operator S1(Span<int> o) => default; } public ref struct S2 { public S1 Field1; public S1 Field2; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (12,48): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return new S2() with { Field1 = outer, Field2 = inner }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field2 = inner").WithArguments("inner").WithLocation(12, 48), // (23,34): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // result = new S2() with { Field1 = inner, Field2 = outer }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field1 = inner").WithArguments("inner").WithLocation(23, 34) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap() { // Similar to test LocalWithNoInitializerEscape but wrapping method is used as receiver for `with` expression var text = @" using System; class Program { static void Main() { S1 sp; Span<int> local = stackalloc int[1]; sp = MayWrap(ref local) with { }; // 1, 2 } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (9,26): error CS8352: Cannot use local 'local' in this context because it may expose referenced variables outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "local").WithArguments("local").WithLocation(9, 26), // (9,14): error CS8347: Cannot use a result of 'Program.MayWrap(ref Span<int>)' in this context because it may expose variables referenced by parameter 'arg' outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeCall, "MayWrap(ref local)").WithArguments("Program.MayWrap(ref System.Span<int>)", "arg").WithLocation(9, 14) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap_02() { var text = @" using System; class Program { static void Main() { Span<int> local = stackalloc int[1]; S1 sp = MayWrap(ref local) with { }; } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_01() { var src = @" #nullable enable record struct B(int X) { static void M(B b) { string? s = null; _ = b with { X = M(out s) }; s.ToString(); } static int M(out string s) { s = ""a""; return 42; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_02() { var src = @" #nullable enable record struct B(string X) { static void M(B b, string? s) { b.X.ToString(); _ = b with { X = s }; // 1 b.X.ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): warning CS8601: Possible null reference assignment. // _ = b with { X = s }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(8, 26)); } [Fact] public void WithExpr_NullableAnalysis_03() { var src = @" #nullable enable record struct B(string? X) { static void M1(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 1 _ = b with { X = s }; if (flag) { b.X.ToString(); } // 2 } static void M2(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 3 b = b with { X = s }; if (flag) { b.X.ToString(); } } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(7, 21), // (9,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(9, 21), // (14,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(14, 21)); } [Fact, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")] public void WithExpr_NullableAnalysis_05() { var src = @" #nullable enable record struct B(string? X, string? Y) { static void M1(bool flag) { B b = new B(""hello"", null); if (flag) { b.X.ToString(); // shouldn't warn b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); // shouldn't warn b.Y.ToString(); } }"; // records should propagate the nullability of the // constructor arguments to the corresponding properties. // https://github.com/dotnet/roslyn/issues/44763 var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(11, 13), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_06() { var src = @" #nullable enable struct B { public string? X { get; init; } public string? Y { get; init; } static void M1(bool flag) { B b = new B { X = ""hello"", Y = null }; if (flag) { b.X.ToString(); b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); b.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(14, 13) ); } [Fact] public void WithExprAssignToRef1() { var src = @" using System; record struct C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X => ref _a[0]; public static void Main() { var c = new C(0) { X = 5 }; Console.WriteLine(c.X); c = c with { X = 1 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 59 (0x3b) .maxstack 2 .locals init (C V_0, //c C V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.0 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_1 IL_000a: call ""ref int C.X.get"" IL_000f: ldc.i4.5 IL_0010: stind.i4 IL_0011: ldloc.1 IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: call ""ref int C.X.get"" IL_001a: ldind.i4 IL_001b: call ""void System.Console.WriteLine(int)"" IL_0020: ldloc.0 IL_0021: stloc.1 IL_0022: ldloca.s V_1 IL_0024: call ""ref int C.X.get"" IL_0029: ldc.i4.1 IL_002a: stind.i4 IL_002b: ldloc.1 IL_002c: stloc.0 IL_002d: ldloca.s V_0 IL_002f: call ""ref int C.X.get"" IL_0034: ldind.i4 IL_0035: call ""void System.Console.WriteLine(int)"" IL_003a: ret }"); } [Fact] public void WithExpressionSameLHS() { var comp = CreateCompilation(@" record struct C(int X) { public static void Main() { var c = new C(0); c = c with { X = 1, X = 2}; } }"); comp.VerifyDiagnostics( // (7,29): error CS1912: Duplicate initialization of member 'X' // c = c with { X = 1, X = 2}; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(7, 29) ); } [Fact] public void WithExpr_AnonymousType_ChangeAllProperties() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { A = Identity(30), B = Identity(40) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,17): error CS8773: Feature 'with on anonymous types' is not available in C# 9.0. Please use language version 10.0 or greater. // var b = Identity(a) with { A = Identity(30), B = Identity(40) }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Identity(a) with { A = Identity(30), B = Identity(40) }").WithArguments("with on anonymous types", "10.0").WithLocation(9, 17) ); comp = CreateCompilation(src, parseOptions: TestOptions.Regular10); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(30) Identity(40) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 30 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: ldc.i4.s 40 IL_0018: call ""int C.Identity<int>(int)"" IL_001d: stloc.0 IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeAllProperties_ReverseOrder() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = Identity(40), A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(40) Identity(30) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 40 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: stloc.0 IL_0017: ldc.i4.s 30 IL_0019: call ""int C.Identity<int>(int)"" IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeNoProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = M2(a) with { }; System.Console.Write(b); }/*</bind>*/ static T M2<T>(T t) { System.Console.Write(""M2 ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "M2 { A = 10, B = 20 }"); verifier.VerifyIL("C.M", @" { // Code size 38 (0x26) .maxstack 2 .locals init (<>f__AnonymousType0<int, int> V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.M2<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0015: ldloc.0 IL_0016: callvirt ""int <>f__AnonymousType0<int, int>.B.get"" IL_001b: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0020: call ""void System.Console.Write(object)"" IL_0025: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.M2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a) with { }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = a with { B = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: ldc.i4.s 30 IL_000b: call ""int C.Identity<int>(int)"" IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var withExpr = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var operation = model.GetOperation(withExpr); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '{ B = Identity(30) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'B = Identity(30)') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'B') Right: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithMethodCallForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: ldc.i4.s 30 IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = (Identity(a) ?? Identity2(a)) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; static T Identity2<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} {R5} } .locals {R3} { CaptureIds: [4] [5] .locals {R4} { CaptureIds: [2] .locals {R5} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(a)') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Leaving: {R5} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B5] Leaving: {R5} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B6] Leaving: {R4} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '(Identity(a ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForValue() { var src = @" C.M(""hello"", ""world""); public class C { public static void M(string hello, string world) /*<bind>*/{ var x = new { A = hello, B = string.Empty }; var y = x with { B = Identity(null) ?? Identity2(world) }; System.Console.Write(y); }/*</bind>*/ static string Identity(string t) => t; static string Identity2(string t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = hello, B = world }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.String A, System.String B> x] [<anonymous type: System.String A, System.String B> y] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'hello') Value: IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'string.Empty') Value: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'new { A = h ... ing.Empty }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'A = hello') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'hello') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'B = string.Empty') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'string.Empty') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [5] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x') Next (Regular) Block[B3] Entering: {R5} .locals {R5} { CaptureIds: [4] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IInvocationOperation (System.String C.Identity(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(null)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(null)') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Leaving: {R5} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Next (Regular) Block[B6] Leaving: {R5} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(world)') Value: IInvocationOperation (System.String C.Identity2(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity2(world)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'world') IParameterReferenceOperation: world (OperationKind.ParameterReference, Type: System.String) (Syntax: 'world') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Value: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B7] Leaving: {R4} } Block[B7] - Block Predecessors: [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x with { B ... y2(world) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B8] Leaving: {R3} } Block[B8] - Block Predecessors: [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(y);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ErrorMember() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { Error = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0117: '<anonymous type: int A>' does not contain a definition for 'Error' // var b = a with { Error = Identity(20) }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("<anonymous type: int A>", "Error").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { Er ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ToString() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { ToString = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS1913: Member 'ToString' cannot be initialized. It is not a field or property. // var b = a with { ToString = Identity(20) }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "ToString").WithArguments("ToString").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { To ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NestedInitializer() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var nested = new { A = 10 }; var a = new { Nested = nested }; var b = a with { Nested = { A = 20 } }; System.Console.Write(b); }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (10,35): error CS1525: Invalid expression term '{' // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(10, 35), // (10,35): error CS1513: } expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(10, 35), // (10,35): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(10, 35), // (10,37): error CS0103: The name 'A' does not exist in the current context // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(10, 37), // (10,44): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(10, 44), // (10,47): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(10, 47), // (11,29): error CS1519: Invalid token '(' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "(").WithArguments("(").WithLocation(11, 29), // (11,31): error CS8124: Tuple must contain at least two elements. // System.Console.Write(b); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(11, 31), // (11,32): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(11, 32), // (13,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> nested] [<anonymous type: <anonymous type: System.Int32 A> Nested> a] [<anonymous type: <anonymous type: System.Int32 A> Nested> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Left: ILocalReferenceOperation: nested (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'nested') Value: ILocalReferenceOperation: nested (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'nested') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'new { Nested = nested }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested = nested') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'new { Nested = nested }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested') Next (Regular) Block[B3] Leaving: {R3} Entering: {R4} } .locals {R4} { CaptureIds: [2] Block[B3] - Block Predecessors: [B2] Statements (3) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '') Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid) (Syntax: 'a with { Nested = ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R4} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'A = 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'A = 20') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'A') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NonAssignmentExpression() { var src = @" public class C { public static void M(int i, int j) /*<bind>*/{ var a = new { A = 10 }; var b = a with { i, j++, M2(), A = 20 }; }/*</bind>*/ static int M2() => 0; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(7, 26), // (7,29): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(7, 29), // (7,34): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(7, 34) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (6) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 C.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { i, ... ), A = 20 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_IndexerAccess() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { [0] = 20 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (7,26): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "[").WithLocation(7, 26), // (7,26): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "[").WithLocation(7, 26), // (7,26): error CS7014: Attributes are not valid in this context. // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[").WithLocation(7, 26), // (7,27): error CS1001: Identifier expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_IdentifierExpected, "0").WithLocation(7, 27), // (7,27): error CS1003: Syntax error, ']' expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SyntaxError, "0").WithArguments("]", "").WithLocation(7, 27), // (7,28): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "]").WithLocation(7, 28), // (7,28): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "]").WithLocation(7, 28), // (7,30): error CS1525: Invalid expression term '=' // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 30), // (7,35): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 35), // (7,36): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(7, 36), // (9,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(9, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { ') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '[0') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '= 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '= 20') Left: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_CannotSet() { var src = @" public class C { public static void M() { var a = new { A = 10 }; a.A = 20; var b = new { B = a }; b.B.A = 30; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // a.A = 20; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "a.A").WithArguments("<anonymous type: int A>.A").WithLocation(7, 9), // (10,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // b.B.A = 30; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.B.A").WithArguments("<anonymous type: int A>.A").WithLocation(10, 9) ); } [Fact] public void WithExpr_AnonymousType_DuplicateMemberInDeclaration() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10, A = 20 }; var b = Identity(a) with { A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (6,31): error CS0833: An anonymous type cannot have multiple properties with the same name // var a = new { A = 10, A = 20 }; Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "A = 20").WithLocation(6, 31) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 $1> a] [<anonymous type: System.Int32 A, System.Int32 $1> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid) (Syntax: 'new { A = 10, A = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: 'A = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsInvalid, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 $1> C.Identity<<anonymous type: System.Int32 A, System.Int32 $1>>(<anonymous type: System.Int32 A, System.Int32 $1> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_DuplicateInitialization() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = Identity(a) with { A = Identity(30), A = Identity(40) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (7,54): error CS1912: Duplicate initialization of member 'A' // var b = Identity(a) with { A = Identity(30), A = Identity(40) }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "A").WithArguments("A").WithLocation(7, 54) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A> C.Identity<<anonymous type: System.Int32 A>>(<anonymous type: System.Int32 A> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo() { var src = @" var x = new { Property = 42 }; var adjusted = x with { Property = x.Property + 2 }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Property = 44 }"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo_NestedWith() { var src = @" var x = new { Property = 42 }; var container = new { Item = x }; var adjusted = container with { Item = x with { Property = x.Property + 2 } }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Item = { Property = 44 } }"); verifier.VerifyDiagnostics(); } [Fact] public void AttributesOnPrimaryConstructorParameters_01() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public readonly record struct Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.RegularPreview, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => a.AttributeClass!.Name is "A" or "B" or "C" or "D")); } } [Fact] public void FieldAsPositionalMember() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record struct A(int X) { public int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(8, 8), // (8,17): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 17) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_Readonly() { var source = @" readonly record struct A(int X) { public int X = X; // 1 } readonly record struct B(int X) { public readonly int X = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS8340: Instance fields of readonly structs must be readonly. // public int X = X; // 1 Diagnostic(ErrorCode.ERR_FieldsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void FieldAsPositionalMember_Fixed() { var src = @" unsafe record struct C(int[] P) { public fixed int P[2]; public int[] X = P; }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,30): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int[]' to match positional parameter 'P'. // unsafe record struct C(int[] P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int[]", "P").WithLocation(2, 30), // (4,22): error CS8908: The type 'int*' may not be used for a field of a record. // public fixed int P[2]; Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P").WithArguments("int*").WithLocation(4, 22) ); } [Fact] public void FieldAsPositionalMember_WrongType() { var source = @" record struct A(int X) { public string X = null; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,21): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record struct A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 21) ); } [Fact] public void FieldAsPositionalMember_DuplicateFields() { var source = @" record struct A(int X) { public int X = 0; public int X = 0; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS0102: The type 'A' already contains a definition for 'X' // public int X = 0; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("A", "X").WithLocation(5, 16) ); } [Fact] public void SyntaxFactory_TypeDeclaration() { var expected = @"record struct Point { }"; AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, SyntaxFactory.TypeDeclaration(SyntaxKind.RecordStructDeclaration, "Point").NormalizeWhitespace().ToString()); } [Fact] public void InterfaceWithParameters() { var src = @" public interface I { } record struct R(int X) : I() { } record struct R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,27): error CS8861: Unexpected argument list. // record struct R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 27), // (10,28): error CS8861: Unexpected argument list. // record struct R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 28) ); } [Fact] public void InterfaceWithParameters_NoPrimaryConstructor() { var src = @" public interface I { } record struct R : I() { } record struct R2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,20): error CS8861: Unexpected argument list. // record struct R : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20), // (10,21): error CS8861: Unexpected argument list. // record struct R2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 21) ); } [Fact] public void InterfaceWithParameters_Struct() { var src = @" public interface I { } struct C : I() { } struct C2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,13): error CS8861: Unexpected argument list. // struct C : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13), // (10,14): error CS8861: Unexpected argument list. // struct C2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14) ); } [Fact] public void BaseArguments_Speculation() { var src = @" record struct R1(int X) : Error1(0, 1) { } record struct R2(int X) : Error2() { } record struct R3(int X) : Error3 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,27): error CS0246: The type or namespace name 'Error1' could not be found (are you missing a using directive or an assembly reference?) // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error1").WithArguments("Error1").WithLocation(2, 27), // (2,33): error CS8861: Unexpected argument list. // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0, 1)").WithLocation(2, 33), // (5,27): error CS0246: The type or namespace name 'Error2' could not be found (are you missing a using directive or an assembly reference?) // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error2").WithArguments("Error2").WithLocation(5, 27), // (5,33): error CS8861: Unexpected argument list. // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(5, 33), // (8,27): error CS0246: The type or namespace name 'Error3' could not be found (are you missing a using directive or an assembly reference?) // record struct R3(int X) : Error3 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error3").WithArguments("Error3").WithLocation(8, 27) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().First(); Assert.Equal("Error1(0, 1)", baseWithargs.ToString()); var speculativeBase = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); Assert.Equal("Error1(0)", speculativeBase.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Skip(1).First(); Assert.Equal("Error2()", baseWithoutargs.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutParens = tree.GetRoot().DescendantNodes().OfType<SimpleBaseTypeSyntax>().Single(); Assert.Equal("Error3", baseWithoutParens.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutParens.SpanStart + 2, speculativeBase, out _)); } } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/CSharpTest/EditAndContinue/TopLevelEditingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class TopLevelEditingTests : EditingTestBase { #region Usings [Fact] public void Using_Global_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" global using D = System.Diagnostics; global using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [global using D = System.Diagnostics;]@2", "Insert [global using System.Collections;]@40"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Delete1() { var src1 = @" using System.Diagnostics; "; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using System.Diagnostics;]@2"); Assert.IsType<UsingDirectiveSyntax>(edits.Edits.First().OldNode); Assert.Null(edits.Edits.First().NewNode); } [Fact] public void Using_Delete2() { var src1 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [using D = System.Diagnostics;]@2", "Delete [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using D = System.Diagnostics;]@2", "Insert [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Collections;]@29 -> [using X = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update2() { var src1 = @" using System.Diagnostics; using X1 = System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X2 = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using X1 = System.Collections;]@29 -> [using X2 = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update3() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Diagnostics;]@2 -> [using System;]@2"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Reorder1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections; using System.Collections.Generic; using System.Diagnostics; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [using System.Diagnostics;]@2 -> @64"); } [Fact] public void Using_InsertDelete1() { var src1 = @" namespace N { using System.Collections; } namespace M { } "; var src2 = @" namespace N { } namespace M { using System.Collections; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@43", "Delete [using System.Collections;]@22"); } [Fact] public void Using_InsertDelete2() { var src1 = @" namespace N { using System.Collections; } "; var src2 = @" using System.Collections; namespace N { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@2", "Delete [using System.Collections;]@22"); } [Fact] public void Using_Delete_ChangesCodeMeaning() { // This test specifically validates the scenario we _don't_ support, namely when inserting or deleting // a using directive, if existing code changes in meaning as a result, we don't issue edits for that code. // If this ever regresses then please buy a lottery ticket because the feature has magically fixed itself. var src1 = @" using System.IO; using DirectoryInfo = N.C; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var src2 = @" using System.IO; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using DirectoryInfo = N.C;]@20"); edits.VerifySemantics(); } [Fact] public void Using_Insert_ForNewCode() { // As distinct from the above, this test validates a real world scenario of inserting a using directive // and changing code that utilizes the new directive to some effect. var src1 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var src2 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Delete_ForOldCode() { var src1 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var src2 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Insert_CreatesAmbiguousCode() { // This test validates that we still issue edits for changed valid code, even when unchanged // code has ambiguities after adding a using. var src1 = @" using System.Threading; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } } }"; var src2 = @" using System.Threading; using System.Timers; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } void M2() { // TimersDescriptionAttribute only exists in System.Timers System.Console.WriteLine(new TimersDescriptionAttribute("""")); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("N.C.M2"))); } #endregion #region Extern Alias [Fact] public void ExternAliasUpdate() { var src1 = "extern alias X;"; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [extern alias X;]@0 -> [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasInsert() { var src1 = ""; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasDelete() { var src1 = "extern alias Y;"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.extern_alias)); } #endregion #region Assembly/Module Attributes [Fact] public void Insert_TopLevelAttribute() { var src1 = ""; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [[assembly: System.Obsolete(\"2\")]]@0", "Insert [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "[assembly: System.Obsolete(\"2\")]", FeaturesResources.attribute)); } [Fact] public void Delete_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"2\")]"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [[assembly: System.Obsolete(\"2\")]]@0", "Delete [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.attribute)); } [Fact] public void Update_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")]"; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[assembly: System.Obsolete(\"1\")]]@0 -> [[assembly: System.Obsolete(\"2\")]]@0", "Update [System.Obsolete(\"1\")]@11 -> [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "System.Obsolete(\"2\")", FeaturesResources.attribute)); } [Fact] public void Reorder_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")][assembly: System.Obsolete(\"2\")]"; var src2 = "[assembly: System.Obsolete(\"2\")][assembly: System.Obsolete(\"1\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [[assembly: System.Obsolete(\"2\")]]@32 -> @0"); edits.VerifyRudeDiagnostics(); } #endregion #region Types [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 public void Type_Kind_Update(string oldKeyword, string newKeyword) { var src1 = oldKeyword + " C { }"; var src2 = newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + oldKeyword + " C { }]@0 -> [" + newKeyword + " C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeKindUpdate, newKeyword + " C")); } [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] public void Type_Kind_Update_Reloadable(string oldKeyword, string newKeyword) { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }]@145 -> [[CreateNewOnMetadataUpdate]" + newKeyword + " C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Modifiers_Static_Remove() { var src1 = "public static class C { }"; var src2 = "public class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public static class C { }]@0 -> [public class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public class C", FeaturesResources.class_)); } [Theory] [InlineData("public")] [InlineData("protected")] [InlineData("private")] [InlineData("private protected")] [InlineData("internal protected")] public void Type_Modifiers_Accessibility_Change(string accessibility) { var src1 = accessibility + " class C { }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + accessibility + " class C { }]@0 -> [class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", FeaturesResources.class_)); } [Theory] [InlineData("public", "public")] [InlineData("internal", "internal")] [InlineData("", "internal")] [InlineData("internal", "")] [InlineData("protected", "protected")] [InlineData("private", "private")] [InlineData("private protected", "private protected")] [InlineData("internal protected", "internal protected")] public void Type_Modifiers_Accessibility_Partial(string accessibilityA, string accessibilityB) { var srcA1 = accessibilityA + " partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = accessibilityB + " partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(), }); } [Fact] public void Type_Modifiers_Internal_Remove() { var src1 = "internal interface C { }"; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Internal_Add() { var src1 = "struct C { }"; var src2 = "internal struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Accessibility_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]public class C { }]@145 -> [[CreateNewOnMetadataUpdate]internal class C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInInterface_Remove(string keyword) { var src1 = "interface C { private " + keyword + " S { } }"; var src2 = "interface C { " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, keyword + " S", GetResource(keyword))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInClass_Add(string keyword) { var src1 = "class C { " + keyword + " S { } }"; var src2 = "class C { private " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPublicInInterface_Add(string keyword) { var src1 = "interface C { " + keyword + " S { } }"; var src2 = "interface C { public " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Add() { var src1 = "public class C { }"; var src2 = "public unsafe class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public class C { }]@0 -> [public unsafe class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Remove() { var src1 = @" using System; unsafe delegate void D(); class C { unsafe class N { } public unsafe event Action<int> A { add { } remove { } } unsafe int F() => 0; unsafe int X; unsafe int Y { get; } unsafe C() {} unsafe ~C() {} } "; var src2 = @" using System; delegate void D(); class C { class N { } public event Action<int> A { add { } remove { } } int F() => 0; int X; int Y { get; } C() {} ~C() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe delegate void D();]@17 -> [delegate void D();]@17", "Update [unsafe class N { }]@60 -> [class N { }]@53", "Update [public unsafe event Action<int> A { add { } remove { } }]@84 -> [public event Action<int> A { add { } remove { } }]@70", "Update [unsafe int F() => 0;]@146 -> [int F() => 0;]@125", "Update [unsafe int X;]@172 -> [int X;]@144", "Update [unsafe int Y { get; }]@191 -> [int Y { get; }]@156", "Update [unsafe C() {}]@218 -> [C() {}]@176", "Update [unsafe ~C() {}]@237 -> [~C() {}]@188"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_DeleteInsert() { var srcA1 = "partial class C { unsafe void F() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), }); } [Fact] public void Type_Modifiers_Ref_Add() { var src1 = "public struct C { }"; var src2 = "public ref struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public ref struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public ref struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_Ref_Remove() { var src1 = "public ref struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public ref struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Add() { var src1 = "public struct C { }"; var src2 = "public readonly struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public readonly struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Remove() { var src1 = "public readonly struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public readonly struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime1() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "[A1]class C { }"; var src2 = attribute + "[A2]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]class C { }]@98 -> [[A2]class C { }]@98"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime2() { var src1 = "[System.Obsolete(\"1\")]class C { }"; var src2 = "[System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\")]class C { }]@0 -> [[System.Obsolete(\"2\")]class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A, B]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[B, A]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[B, A]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Change_Reloadable() { var attributeSrc = @" public class A1 : System.Attribute { } public class A2 : System.Attribute { } public class A3 : System.Attribute { } "; var src1 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A1, A2]class C { }"; var src2 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A2, A3]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate, A1, A2]class C { }]@267 -> [[CreateNewOnMetadataUpdate, A2, A3]class C { }]@267"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableRemove() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableAdd() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_ReloadableBase() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@48 -> [[A]class C { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Reorder1() { var src1 = "[A(1), B(2), C(3)]class C { }"; var src2 = "[C(3), A(1), B(2)]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(1), B(2), C(3)]class C { }]@0 -> [[C(3), A(1), B(2)]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_Reorder2() { var src1 = "[A, B, C]class C { }"; var src2 = "[B, C, A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B, C]class C { }]@0 -> [[B, C, A]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_ReorderAndUpdate_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[System.Obsolete(\"1\"), A, B]class C { }"; var src2 = attribute + "[A, B, System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), A, B]class C { }]@96 -> [[A, B, System.Obsolete(\"2\")]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Rename(string keyword) { var src1 = keyword + " C { }"; var src2 = keyword + " D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + keyword + " C { }]@0 -> [" + keyword + " D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, keyword + " D", GetResource(keyword))); } [Fact] public void Type_Rename_AddAndDeleteMember() { var src1 = "class C { int x = 1; }"; var src2 = "class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { int x = 1; }]@0 -> [class D { void F() { } }]@0", "Insert [void F() { }]@10", "Insert [()]@16", "Delete [int x = 1;]@10", "Delete [int x = 1]@10", "Delete [x = 1]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { }]@145 -> [[CreateNewOnMetadataUpdate]class D { }]@145"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable_AddAndDeleteMember() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { int x = 1; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { int x = 1; }]@145 -> [[CreateNewOnMetadataUpdate]class D { void F() { } }]@145", "Insert [void F() { }]@182", "Insert [()]@188", "Delete [int x = 1;]@182", "Delete [int x = 1]@182", "Delete [x = 1]@186"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] public void Interface_NoModifiers_Insert() { var src1 = ""; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { } "; var src2 = "namespace N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoType_Insert() { var src1 = "interface N { }"; var src2 = "interface N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_Insert() { var src1 = ""; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_Insert() { var src1 = ""; var src2 = "struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_BaseType_Add_Unchanged() { var src1 = "class C { }"; var src2 = "class C : object { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : object { }]@0"); edits.VerifySemantics(); } [Fact] public void Type_BaseType_Add_Changed() { var src1 = "class C { }"; var src2 = "class C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("string[]", "string[]?")] [InlineData("object", "dynamic")] [InlineData("dynamic?", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseType_Update_CompileTimeTypeUnchanged() { var src1 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<A> {}"; var src2 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Add() { var src1 = "class C { }"; var src2 = "class C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseInterface_Delete_Inherited() { var src1 = @" interface B {} interface A : B {} class C : A, B {} "; var src2 = @" interface B {} interface A : B {} class C : A {} "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Reorder() { var src1 = "class C : IGoo, IBar { }"; var src2 = "class C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C : IGoo, IBar { }]@0 -> [class C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseInterface_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseInterface_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_Base_Partial() { var srcA1 = "partial class C : B, I { }"; var srcB1 = "partial class C : J { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C : B, I, J { }"; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Base_Partial_InsertDeleteAndUpdate() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "partial class C : D { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "partial class C", FeaturesResources.class_) }), DocumentResults(), }); } [Fact] public void Type_Base_InsertDelete() { var srcA1 = ""; var srcB1 = "class C : B, I { }"; var srcA2 = "class C : B, I { }"; var srcB2 = ""; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Reloadable_NotSupportedByRuntime() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(1); } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void F()", "CreateNewOnMetadataUpdateAttribute")); } [Fact] public void Type_Insert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract class C<T> { public abstract void F(); public virtual void G() {} public override string ToString() => null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Insert_NotSupportedByRuntime() { var src1 = @" public class C { void F() { } }"; var src2 = @" public class C { void F() { } } public class D { void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "public class D", FeaturesResources.class_)); } [Fact] public void Type_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + ""; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"))); } [Fact] public void InterfaceInsert() { var src1 = ""; var src2 = @" public interface I { void F(); static void G() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RefStructInsert() { var src1 = ""; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_ReadOnly_Insert() { var src1 = ""; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_RefModifier_Add() { var src1 = "struct X { }"; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [ref struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "ref struct X", CSharpFeaturesResources.struct_)); } [Fact] public void Struct_ReadonlyModifier_Add() { var src1 = "struct X { }"; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly struct X", SyntaxFacts.GetText(SyntaxKind.StructKeyword))); } [Theory] [InlineData("ref")] [InlineData("readonly")] public void Struct_Modifiers_Partial_InsertDelete(string modifier) { var srcA1 = modifier + " partial struct S { }"; var srcB1 = "partial struct S { }"; var srcA2 = "partial struct S { }"; var srcB2 = modifier + " partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact] public void Class_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; }]@219", "Insert [public override string Get() => string.Empty;]@272", "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@298", "Insert [()]@345"); // Here we add a class implementing an interface and a method inside it with explicit interface specifier. // We want to be sure that adding the method will not tirgger a rude edit as it happens if adding a single method with explicit interface specifier. edits.VerifyRudeDiagnostics(); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void Interface_InsertMembers() { var src1 = @" using System; interface I { } "; var src2 = @" using System; interface I { static int StaticField = 10; static void StaticMethod() { } void VirtualMethod1() { } virtual void VirtualMethod2() { } abstract void AbstractMethod(); sealed void NonVirtualMethod() { } public static int operator +(I a, I b) => 1; static int StaticProperty1 { get => 1; set { } } static int StaticProperty2 => 1; virtual int VirtualProperty1 { get => 1; set { } } virtual int VirtualProperty2 { get => 1; } int VirtualProperty3 { get => 1; set { } } int VirtualProperty4 { get => 1; } abstract int AbstractProperty1 { get; set; } abstract int AbstractProperty2 { get; } sealed int NonVirtualProperty => 1; int this[byte virtualIndexer] => 1; int this[sbyte virtualIndexer] { get => 1; } virtual int this[ushort virtualIndexer] { get => 1; set {} } virtual int this[short virtualIndexer] { get => 1; set {} } abstract int this[uint abstractIndexer] { get; set; } abstract int this[int abstractIndexer] { get; } sealed int this[ulong nonVirtualIndexer] { get => 1; set {} } sealed int this[long nonVirtualIndexer] { get => 1; set {} } static event Action StaticEvent; static event Action StaticEvent2 { add { } remove { } } event Action VirtualEvent { add { } remove { } } abstract event Action AbstractEvent; sealed event Action NonVirtualEvent { add { } remove { } } abstract class C { } interface J { } enum E { } delegate void D(); } "; var edits = GetTopEdits(src1, src2); // TODO: InsertIntoInterface errors are reported due to https://github.com/dotnet/roslyn/issues/37128. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoInterface, "static void StaticMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "void VirtualMethod1()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "virtual void VirtualMethod2()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "abstract void AbstractMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed void NonVirtualMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertOperator, "public static int operator +(I a, I b)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty3", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty4", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[sbyte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[ushort virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[short virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[uint abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[int abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[ulong nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[long nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "static event Action StaticEvent2", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertVirtual, "event Action VirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed event Action NonVirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticField = 10", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticEvent", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertVirtual, "AbstractEvent", CSharpFeaturesResources.event_field)); } [Fact] public void Interface_InsertDelete() { var srcA1 = @" interface I { static void M() { } } "; var srcB1 = @" "; var srcA2 = @" "; var srcB2 = @" interface I { static void M() { } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("M")) }), }); } [Fact] public void Type_Generic_InsertMembers() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "void M()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int this[int i]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoGenericType, "event Action E", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoGenericType, "EF", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F1", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F2", FeaturesResources.field)); } [Fact] public void Type_Generic_InsertMembers_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event System.Action E { add {} remove {} } event System.Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Generic_DeleteInsert() { var srcA1 = @" class C<T> { void F() {} } struct S<T> { void F() {} } interface I<T> { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "struct S<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "interface I<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }) }); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Type_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C<T> { void F() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C<T, S> { int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Delete() { var src1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var src2 = ""; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(CSharpFeaturesResources.struct_, "S")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.interface_, "I"))); } [Fact] public void Type_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var src2 = ReloadableAttributeSrc; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void Type_Partial_DeleteDeclaration() { var srcA1 = "partial class C { void F() {} void M() { } }"; var srcB1 = "partial class C { void G() {} }"; var srcA2 = ""; var srcB2 = "partial class C { void G() {} void M() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.method, "C.F()")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("M")), }) }); } [Fact] public void Type_Partial_InsertFirstDeclaration() { var src1 = ""; var src2 = "partial class C { void F() {} }"; GetTopEdits(src1, src2).VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C"), preserveLocalVariables: false) }); } [Fact] public void Type_Partial_InsertSecondDeclaration() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G"), preserveLocalVariables: false) }), }); } [Fact] public void Type_Partial_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact] public void Type_DeleteInsert() { var srcA1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_DeleteInsert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc; var srcB2 = "[CreateNewOnMetadataUpdate]class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")), }) }); } [Fact] public void Type_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; // TODO: The methods without bodies do not need to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_Attribute_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" abstract class C { [System.Obsolete]public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { [System.Obsolete]void G(); void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_DeleteInsert_DataMembers() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialSplit() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB1 = ""; var srcA2 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB2 = @" partial class C { public int P { get; set; } = 3; } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialMerge() { var srcA1 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB1 = @" partial class C { public int P { get; set; } = 3; }"; var srcA2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB2 = @" "; // note that accessors are not updated since they do not have bodies EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }), DocumentResults() }); } #endregion #region Records [Fact] public void Record_Partial_MovePrimaryConstructor() { var src1 = @" partial record C { } partial record C(int X);"; var src2 = @" partial record C(int X); partial record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Name_Update() { var src1 = "record C { }"; var src2 = "record D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "record D", CSharpFeaturesResources.record_)); } [Fact] public void RecordStruct_NoModifiers_Insert() { var src1 = ""; var src2 = "record struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_AddField() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { private int _y = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "_y = 0", FeaturesResources.field, CSharpFeaturesResources.record_struct)); } [Fact] public void RecordStruct_AddProperty() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { public int Y { get; set; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "public int Y { get; set; } = 0;", FeaturesResources.auto_property, CSharpFeaturesResources.record_struct)); } [Fact] public void Record_NoModifiers_Insert() { var src1 = ""; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_BaseTypeUpdate1() { var src1 = "record C { }"; var src2 = "record C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseTypeUpdate2() { var src1 = "record C : D1 { }"; var src2 = "record C : D2 { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : D1 { }]@0 -> [record C : D2 { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate1() { var src1 = "record C { }"; var src2 = "record C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate2() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate3() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void RecordInsert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract record C<T> { public abstract void F(); public virtual void G() {} public override void H() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_PrintMembers() { var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_ImplementSynthesized_PrintMembers() { var src1 = "record struct C { }"; var src2 = @" record struct C { private bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_WrongParameterName() { // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder sb) { return false; } public virtual bool Equals(C rhs) { return false; } protected C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected virtual bool PrintMembers(System.Text.StringBuilder sb)", "PrintMembers(System.Text.StringBuilder builder)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "public virtual bool Equals(C rhs)", "Equals(C other)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected C(C other)", "C(C original)")); } [Fact] public void Record_ImplementSynthesized_ToString() { var src1 = "record C { }"; var src2 = @" record C { public override string ToString() { return ""R""; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_ToString() { var src1 = @" record C { public override string ToString() { return ""R""; } }"; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_Primary() { var src1 = "record C(int X);"; var src2 = "record C(int X, int Y);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int Y", FeaturesResources.parameter)); } [Fact] public void Record_AddProperty_NotPrimary() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithConstructor() { var src1 = @" record C(int X) { public C(string fromAString) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } public C(string fromAString) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithExplicitMembers() { var src1 = @" record C(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithInitializer() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExplicitMembers() { var src1 = @" record C(int X) { public C(C other) { } }"; var src2 = @" record C(int X) { private int _y; public C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializer() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y = 1; }"; var syntaxMap = GetSyntaxMap(src1, src2); var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializerAndExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_DeleteField() { var src1 = "record C(int X) { private int _y; }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.field, "_y"))); } [Fact] public void Record_DeleteProperty_Primary() { var src1 = "record C(int X, int Y) { }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.parameter, "int Y"))); } [Fact] public void Record_DeleteProperty_NotPrimary() { var src1 = "record C(int X) { public int P { get; set; } }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "P"))); } [Fact] public void Record_ImplementSynthesized_Property() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get { return 4; } init { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithExpressionBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_InitToSet() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterWithSet, "public int X", "X")); } [Fact] public void Record_ImplementSynthesized_Property_MakeReadOnly() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterAsReadOnly, "public int X", "X")); } [Fact] public void Record_UnImplementSynthesized_Property() { var src1 = @" record C(int X) { public int X { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithExpressionBody() { var src1 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithBody() { var src1 = @" record C(int X) { public int X { get { return 4; } init { } } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get; init; } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_ImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_MoveProperty_Partial() { var srcA1 = @" partial record C(int X) { public int Y { get; init; } }"; var srcB1 = @" partial record C; "; var srcA2 = @" partial record C(int X); "; var srcB2 = @" partial record C { public int Y { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").SetMethod) }), }); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializer() { var src1 = @" record C(int X) { public int X { get; init; } = 1; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializerMatchingCompilerGenerated() { var src1 = @" record C(int X) { public int X { get; init; } = X; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Property_Delete_NotPrimary() { var src1 = @" record C(int X) { public int Y { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "Y"))); } [Fact] public void Record_PropertyInitializer_Update_NotPrimary() { var src1 = "record C { int X { get; } = 0; }"; var src2 = "record C { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true)); } [Fact] public void Record_PropertyInitializer_Update_Primary() { var src1 = "record C(int X) { int X { get; } = 0; }"; var src2 = "record C(int X) { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); } #endregion #region Enums [Fact] public void Enum_NoModifiers_Insert() { var src1 = ""; var src2 = "enum C { A }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { }"; var src2 = attribute + "[A]enum E { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum E { }]@48 -> [[A]enum E { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "enum E", FeaturesResources.enum_)); } [Fact] public void Enum_Member_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A]X }"; var src2 = attribute + "enum E { X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]X]@57 -> [X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { X }"; var src2 = attribute + "enum E { [A]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [X]@57 -> [[A]X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Update() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A1]X }"; var src2 = attribute + "enum E { [A2]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]X]@107 -> [[A2]X]@107"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A2]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_InsertDeleteAndUpdate() { var srcA1 = ""; var srcB1 = "enum N { A = 1 }"; var srcA2 = "enum N { [System.Obsolete]A = 1 }"; var srcB2 = ""; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.A")) }), DocumentResults() }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Enum_Rename() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Colors { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Colors { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "enum Colors", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : ushort { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : ushort { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add_Unchanged() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : int { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : int { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Update() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color : long { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color : long { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Delete_Unchanged() { var src1 = "enum Color : int { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : int { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Delete_Changed() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityChange() { var src1 = "public enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityNoChange() { var src1 = "internal enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void EnumInitializerUpdate() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 3, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Blue = 2]@22 -> [Blue = 3]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 3", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate2() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1 << 0, Blue = 2 << 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@13 -> [Red = 1 << 0]@13", "Update [Blue = 2]@22 -> [Blue = 2 << 1]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 2 << 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate3() { var src1 = "enum Color { Red = int.MinValue }"; var src2 = "enum Color { Red = int.MaxValue }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = int.MinValue]@13 -> [Red = int.MaxValue]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = int.MaxValue", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 1 }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 2 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@185 -> [Red = 2]@185"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("Color"))); } [Fact] public void EnumInitializerAdd() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Red = 1]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerDelete() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red = 1]@13 -> [Red]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, Blue}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberAdd2() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd3() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue,}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red, Blue,}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberUpdate() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Orange }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Orange]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "Orange", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberDelete() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red, Blue}]@0 -> [enum Color { Red }]@0", "Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [Fact] public void EnumMemberDelete2() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd_WithInitializer() { var src1 = "enum Color { Red = 1 }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1 }]@0 -> [enum Color { Red = 1, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete_WithInitializer() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red = 1 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, }]@0 -> [enum Color { Red = 1 }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } #endregion #region Delegates [Fact] public void Delegates_NoModifiers_Insert() { var src1 = ""; var src2 = "delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Public_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { public delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate void D();]@10", "Insert [()]@32"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Generic_Insert() { var src1 = "class C { }"; var src2 = "class C { private delegate void D<T>(T a); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private delegate void D<T>(T a);]@10", "Insert [<T>]@33", "Insert [(T a)]@36", "Insert [T]@34", "Insert [T a]@37"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Delete() { var src1 = "class C { private delegate void D(); }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [private delegate void D();]@10", "Delete [()]@33"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.delegate_, "D"))); } [Fact] public void Delegates_Rename() { var src1 = "public delegate void D();"; var src2 = "public delegate void Z();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [public delegate void Z();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "public delegate void Z()", FeaturesResources.delegate_)); } [Fact] public void Delegates_Accessibility_Update() { var src1 = "public delegate void D();"; var src2 = "private delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [private delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@39 -> [[return: A]public delegate int D(int a);]@39"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_Parameter_Delete() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.parameter, "int a"))); } [Fact] public void Delegates_Parameter_Rename() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "int b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Update() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(byte a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [byte a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "byte a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@70 -> [[A]int a]@70"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@61 -> [[A]int a]@61"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_TypeParameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<T>]@21", "Insert [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "T", FeaturesResources.type_parameter)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Delegates_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D<out T>();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D<in T, out S>(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_TypeParameter_Delete() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<T>]@21", "Delete [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void Delegates_TypeParameter_Rename() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<S>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [S]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void Delegates_TypeParameter_Variance1() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance2() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance3() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_AddAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D<T>();"; var src2 = attribute + "public delegate int D<[A]T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@70 -> [[A]T]@70"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_Attribute_Add_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public delegate int D(int a)", FeaturesResources.delegate_)); } [Fact] public void Delegates_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Attribute_Add_WithReturnTypeAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A][A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[return: A][A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertWhole() { var src1 = ""; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate int D(in int b);]@0", "Insert [(in int b)]@21", "Insert [in int b]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_Parameter_Update() { var src1 = "public delegate int D(int b);"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@22 -> [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Insert() { var src1 = ""; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate ref readonly int D();]@0", "Insert [()]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate ref readonly int D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate ref readonly int D()", FeaturesResources.delegate_)); } #endregion #region Nested Types [Fact] public void NestedClass_ClassMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { } class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class D { }]@10 -> @12"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassMove2() { var src1 = @"class C { class D { } class E { } class F { } }"; var src2 = @"class C { class D { } class F { } } class E { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class E { }]@23 -> @37"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class E", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassInsertMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { class E { class D { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class E { class D { } }]@10", "Move [class D { }]@10 -> @20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_Insert1() { var src1 = @"class C { }"; var src2 = @"class C { class D { class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class D { class E { } }]@10", "Insert [class E { }]@20"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert2() { var src1 = @"class C { }"; var src2 = @"class C { protected class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [protected class D { public class E { } }]@10", "Insert [public class E { }]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert3() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public class E { } }]@10", "Insert [public class E { }]@28"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert4() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public D(int a, int b) { } public int P { get; set; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public D(int a, int b) { } public int P { get; set; } }]@10", "Insert [public D(int a, int b) { }]@28", "Insert [public int P { get; set; }]@55", "Insert [(int a, int b)]@36", "Insert [{ get; set; }]@68", "Insert [int a]@37", "Insert [int b]@44", "Insert [get;]@70", "Insert [set;]@75"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable1() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable2() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable3() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable4() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_Insert_Member_Reloadable() { var src1 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { } }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { int x; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_InsertMemberWithInitializer1() { var src1 = @" class C { }"; var src2 = @" class C { private class D { public int P = 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"), preserveLocalVariables: false) }); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public extern D(); public static extern int P { [DllImport(""msvcrt.dll"")]get; [DllImport(""msvcrt.dll"")]set; } [DllImport(""msvcrt.dll"")] public static extern int puts(string c); [DllImport(""msvcrt.dll"")] public static extern int operator +(D d, D g); [DllImport(""msvcrt.dll"")] public static extern explicit operator int (D d); } } "; var edits = GetTopEdits(src1, src2); // Adding P/Invoke is not supported by the CLR. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "public extern D()", FeaturesResources.constructor), Diagnostic(RudeEditKind.InsertExtern, "public static extern int P", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "public static extern int puts(string c)", FeaturesResources.method), Diagnostic(RudeEditKind.InsertExtern, "public static extern int operator +(D d, D g)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertExtern, "public static extern explicit operator int (D d)", CSharpFeaturesResources.conversion_operator)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_VirtualAbstract() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public abstract int P { get; } public abstract int this[int i] { get; } public abstract int puts(string c); public virtual event Action E { add { } remove { } } public virtual int Q { get { return 1; } } public virtual int this[string i] { get { return 1; } } public virtual int M(string c) { return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_TypeReorder1() { var src1 = @"class C { struct E { } class F { } delegate void D(); interface I {} }"; var src2 = @"class C { class F { } interface I {} delegate void D(); struct E { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [struct E { }]@10 -> @56", "Reorder [interface I {}]@54 -> @22"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_MethodDeleteInsert() { var src1 = @"public class C { public void goo() {} }"; var src2 = @"public class C { private class D { public void goo() {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public void goo() {} }]@17", "Insert [public void goo() {}]@35", "Insert [()]@50", "Delete [public void goo() {}]@17", "Delete [()]@32"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "public class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void NestedClass_ClassDeleteInsert() { var src1 = @"public class C { public class X {} }"; var src2 = @"public class C { public class D { public class X {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public class D { public class X {} }]@17", "Move [public class X {}]@17 -> @34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "public class X", FeaturesResources.class_)); } /// <summary> /// A new generic type can be added whether it's nested and inherits generic parameters from the containing type, or top-level. /// </summary> [Fact] public void NestedClassGeneric_Insert() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { class D {} struct S {} enum N {} interface I {} delegate void D(); } class D<T> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedEnum_InsertMember() { var src1 = "struct S { enum N { A = 1 } }"; var src2 = "struct S { enum N { A = 1, B = 2 } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum N { A = 1 }]@11 -> [enum N { A = 1, B = 2 }]@11", "Insert [B = 2]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value)); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "A = 2", FeaturesResources.enum_value), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateBase() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N : uint { A = 1 } }"; var srcA2 = "partial struct S { enum N : int { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum N", FeaturesResources.enum_), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndInsertMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1, B = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( // delegate does not have any user-defined method body and this does not need a PDB update semanticEdits: NoSemanticEdits), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(int x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingParameterTypes, "delegate void D(int x)", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate ref int D(); }"; var srcA2 = "partial struct S { delegate ref readonly int D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.TypeUpdate, "delegate ref readonly int D()", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterValue() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(int x = 1); }"; var srcA2 = "partial struct S { delegate void D(int x = 2); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults() }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndChange() { var srcA1 = "partial struct S { partial class C { void F1() {} } }"; var srcB1 = "partial struct S { partial class C { void F2(byte x) {} } }"; var srcC1 = "partial struct S { }"; var srcA2 = "partial struct S { partial class C { void F1() {} } }"; var srcB2 = "partial struct S { }"; var srcC2 = "partial struct S { partial class C { void F2(int x) {} } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F2(byte x)")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("S").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }) }); } [Fact] public void Type_Partial_AddMultiple() { var srcA1 = ""; var srcB1 = ""; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_Attribute() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "[A]partial class C { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_TypeParameterAttribute_NotSupportedByRuntime() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<[A]T> { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<[A]T>"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteAndChange_Constraint() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<T> where T : new() { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<T>"), Diagnostic(RudeEditKind.ChangingConstraints, "where T : new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : new()") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteRefactor() { var srcA1 = "partial class C : I { void F() { } }"; var srcB1 = "[A][B]partial class C : J { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C : I, J { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; var srcE = "interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE, srcE) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G")) }), DocumentResults(), }); } [Fact] public void Type_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C { }" + attributes; var srcB1 = "partial class C { }"; var srcA2 = "[A]partial class C { }" + attributes; var srcB2 = "[B]partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting() { var srcA1 = "partial class C { void F() { } }"; var srcB1 = "[A,B]partial class C { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")) }), }); } [Fact] public void Type_Partial_InsertDeleteChangeMember() { var srcA1 = "partial class C { void F(int y = 1) { } }"; var srcB1 = "partial class C { void G(int x = 1) { } }"; var srcC1 = ""; var srcA2 = ""; var srcB2 = "partial class C { void G(int x = 2) { } }"; var srcC2 = "partial class C { void F(int y = 2) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int y = 2", FeaturesResources.parameter) }), }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndInsertVirtual() { var srcA1 = "partial interface I { partial class C { virtual void F1() {} } }"; var srcB1 = "partial interface I { partial class C { virtual void F2() {} } }"; var srcC1 = "partial interface I { partial class C { } }"; var srcD1 = "partial interface I { partial class C { } }"; var srcE1 = "partial interface I { }"; var srcF1 = "partial interface I { }"; var srcA2 = "partial interface I { partial class C { } }"; var srcB2 = ""; var srcC2 = "partial interface I { partial class C { virtual void F1() {} } }"; // move existing virtual into existing partial decl var srcD2 = "partial interface I { partial class C { virtual void N1() {} } }"; // insert new virtual into existing partial decl var srcE2 = "partial interface I { partial class C { virtual void F2() {} } }"; // move existing virtual into a new partial decl var srcF2 = "partial interface I { partial class C { virtual void N2() {} } }"; // insert new virtual into new partial decl EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE1, srcE2), GetTopEdits(srcF1, srcF2) }, new[] { // A DocumentResults(), // B DocumentResults(), // C DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F1")) }), // D DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N1()", FeaturesResources.method) }), // E DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }), // F DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N2()", FeaturesResources.method) }), }); } #endregion #region Namespaces [Fact] public void Namespace_Insert() { var src1 = @""; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_InsertNested() { var src1 = @"namespace C { }"; var src2 = @"namespace C { namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_DeleteNested() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_Move() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { } namespace D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [namespace D { }]@14 -> @16"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_Reorder1() { var src1 = @"namespace C { namespace D { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@30 -> @30", "Reorder [namespace E { }]@42 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_Reorder2() { var src1 = @"namespace C { namespace D1 { } namespace D2 { } namespace D3 { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D1 { } namespace D2 { } namespace D3 { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@65 -> @65", "Reorder [namespace E { }]@77 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_FileScoped_Insert() { var src1 = @""; var src2 = @"namespace C;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_FileScoped_Delete() { var src1 = @"namespace C;"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_)); } #endregion #region Members [Fact] public void PartialMember_DeleteInsert_SingleDocument() { var src1 = @" using System; partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1; int F2; } partial class C { } "; var src2 = @" using System; partial class C { } partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void M() {}]@68", "Insert [int P1 { get; set; }]@85", "Insert [int P2 { get => 1; set {} }]@111", "Insert [int this[int i] { get => 1; set {} }]@144", "Insert [int this[byte i] { get => 1; set {} }]@186", "Insert [event Action E { add {} remove {} }]@229", "Insert [event Action EF;]@270", "Insert [int F1, F2;]@292", "Insert [()]@74", "Insert [{ get; set; }]@92", "Insert [{ get => 1; set {} }]@118", "Insert [[int i]]@152", "Insert [{ get => 1; set {} }]@160", "Insert [[byte i]]@194", "Insert [{ get => 1; set {} }]@203", "Insert [{ add {} remove {} }]@244", "Insert [Action EF]@276", "Insert [int F1, F2]@292", "Insert [get;]@94", "Insert [set;]@99", "Insert [get => 1;]@120", "Insert [set {}]@130", "Insert [int i]@153", "Insert [get => 1;]@162", "Insert [set {}]@172", "Insert [byte i]@195", "Insert [get => 1;]@205", "Insert [set {}]@215", "Insert [add {}]@246", "Insert [remove {}]@253", "Insert [EF]@283", "Insert [F1]@296", "Insert [F2]@300", "Delete [void M() {}]@43", "Delete [()]@49", "Delete [int P1 { get; set; }]@60", "Delete [{ get; set; }]@67", "Delete [get;]@69", "Delete [set;]@74", "Delete [int P2 { get => 1; set {} }]@86", "Delete [{ get => 1; set {} }]@93", "Delete [get => 1;]@95", "Delete [set {}]@105", "Delete [int this[int i] { get => 1; set {} }]@119", "Delete [[int i]]@127", "Delete [int i]@128", "Delete [{ get => 1; set {} }]@135", "Delete [get => 1;]@137", "Delete [set {}]@147", "Delete [int this[byte i] { get => 1; set {} }]@161", "Delete [[byte i]]@169", "Delete [byte i]@170", "Delete [{ get => 1; set {} }]@178", "Delete [get => 1;]@180", "Delete [set {}]@190", "Delete [event Action E { add {} remove {} }]@204", "Delete [{ add {} remove {} }]@219", "Delete [add {}]@221", "Delete [remove {}]@228", "Delete [event Action EF;]@245", "Delete [Action EF]@251", "Delete [EF]@258", "Delete [int F1;]@267", "Delete [int F1]@267", "Delete [F1]@271", "Delete [int F2;]@280", "Delete [int F2]@280", "Delete [F2]@284"); EditAndContinueValidation.VerifySemantics( new[] { edits }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod, preserveLocalVariables: false), }) }); } [Fact] public void PartialMember_InsertDelete_MultipleDocuments() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() {} }"; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"), preserveLocalVariables: false) }), DocumentResults() }); } [Fact] public void PartialMember_DeleteInsert_MultipleDocuments() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"), preserveLocalVariables: false) }) }); } [Fact] public void PartialMember_DeleteInsert_GenericMethod() { var srcA1 = "partial class C { void F<T>() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F<T>() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<T>()"), Diagnostic(RudeEditKind.GenericMethodUpdate, "T") }) }); } [Fact] public void PartialMember_DeleteInsert_GenericType() { var srcA1 = "partial class C<T> { void F() {} }"; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<T> { }"; var srcB2 = "partial class C<T> { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()") }) }); } [Fact] public void PartialMember_DeleteInsert_Destructor() { var srcA1 = "partial class C { ~C() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { ~C() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("Finalize"), preserveLocalVariables: false), }) }); } [Fact] public void PartialNestedType_InsertDeleteAndChange() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { class D { void M() {} } interface I { } }"; var srcA2 = "partial class C { class D : I { void M() {} } interface I { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class D", FeaturesResources.class_), }), DocumentResults() }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void PartialMember_RenameInsertDelete() { // The syntactic analysis for A and B produce rename edits since it doesn't see that the member was in fact moved. // TODO: Currently, we don't even pass rename edits to semantic analysis where we could handle them as updates. var srcA1 = "partial class C { void F1() {} }"; var srcB1 = "partial class C { void F2() {} }"; var srcA2 = "partial class C { void F2() {} }"; var srcB2 = "partial class C { void F1() {} }"; // current outcome: GetTopEdits(srcA1, srcA2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F2()", FeaturesResources.method)); GetTopEdits(srcB1, srcB2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F1()", FeaturesResources.method)); // correct outcome: //EditAndContinueValidation.VerifySemantics( // new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, // new[] // { // DocumentResults(semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), // }), // DocumentResults( // semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F1")), // }) // }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodBodyError() { var srcA1 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; } } "; var srcB1 = @" using System.Collections.Generic; partial class C { } "; var srcA2 = @" using System.Collections.Generic; partial class C { } "; var srcB2 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; yield return 2; } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdatePropertyAccessors() { var srcA1 = "partial class C { int P { get => 1; set { Console.WriteLine(1); } } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateAutoProperty() { var srcA1 = "partial class C { int P => 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P => 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_AddFieldInitializer() { var srcA1 = "partial class C { int f; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f = 1; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_RemoveFieldInitializer() { var srcA1 = "partial class C { int f = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_ConstructorWithInitializers() { var srcA1 = "partial class C { int f = 1; C(int x) { f = x; } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { int f = 1; }"; var srcB2 = "partial class C { C(int x) { f = x + 1; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F() {} }"; var srcA2 = "partial struct S { void F(int x) {} }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodParameterType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(int x); }"; var srcA2 = "partial struct S { void F(byte x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F(int x)")) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddTypeParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(); }"; var srcA2 = "partial struct S { void F<T>(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertGenericMethod, "void F<T>()", FeaturesResources.method) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Methods [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Method_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F() => 0; }"; var src2 = "class C { " + newModifiers + "int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F() => 0;]@10 -> [" + newModifiers + "int F() => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F()", FeaturesResources.method)); } [Fact] public void Method_NewModifier_Add() { var src1 = "class C { int F() => 0; }"; var src2 = "class C { new int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int F() => 0;]@10 -> [new int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_NewModifier_Remove() { var src1 = "class C { new int F() => 0; }"; var src2 = "class C { int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [new int F() => 0;]@10 -> [int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_ReadOnlyModifier_Add_InMutableStruct() { var src1 = @" struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct1() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" readonly struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough the body nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IMethodSymbol>("M"))); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct2() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "struct S", "struct")); } [Fact] public void Method_AsyncModifier_Remove() { var src1 = @" class Test { public async Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public Task<int> WaitAsync() { return Task.FromResult(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "public Task<int> WaitAsync()", FeaturesResources.method)); } [Fact] public void Method_AsyncModifier_Add() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void Method_AsyncModifier_Add_NotSupported() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodAsync, "public async Task<int> WaitAsync()")); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Method_ReturnType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Method_ReturnType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " M()", FeaturesResources.method)); } [Fact] public void Method_Update() { var src1 = @" class C { static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); } } "; var src2 = @" class C { static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); }]@18 -> [static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); }]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact] public void MethodWithExpressionBody_Update() { var src1 = @" class C { static int Main(string[] args) => F(1); static int F(int a) => 1; } "; var src2 = @" class C { static int Main(string[] args) => F(2); static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static int Main(string[] args) => F(1);]@18 -> [static int Main(string[] args) => F(2);]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void MethodWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int M(int a) => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int M(int a) => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M(int a) => new Func<int>(() => a + 1)();]@35 -> [int M(int a) => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact] public void MethodWithExpressionBody_ToBlockBody() { var src1 = "class C { static int F(int a) => 1; }"; var src2 = "class C { static int F(int a) { return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => 1;]@10 -> [static int F(int a) { return 2; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithBlockBody_ToExpressionBody() { var src1 = "class C { static int F(int a) { return 2; } }"; var src2 = "class C { static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) { return 2; }]@10 -> [static int F(int a) => 1;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithLambda_Update() { var src1 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; } } "; var src2 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap[0]) }); } [Fact] public void MethodUpdate_LocalVariableDeclaration() { var src1 = @" class C { static void Main(string[] args) { int x = 1; Console.WriteLine(x); } } "; var src2 = @" class C { static void Main(string[] args) { int x = 2; Console.WriteLine(x); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int x = 1; Console.WriteLine(x); }]@18 -> [static void Main(string[] args) { int x = 2; Console.WriteLine(x); }]@18"); } [Fact] public void Method_Delete() { var src1 = @" class C { void goo() { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [void goo() { }]@18", "Delete [()]@26"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void MethodWithExpressionBody_Delete() { var src1 = @" class C { int goo() => 1; } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int goo() => 1;]@18", "Delete [()]@25"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_WithParameterAndAttribute() { var src1 = @" class C { [Obsolete] void goo(int a) { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[Obsolete] void goo(int a) { }]@18", "Delete [(int a)]@42", "Delete [int a]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo(int a)"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int puts(string c); } "; var src2 = @" using System; using System.Runtime.InteropServices; class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[DllImport(""msvcrt.dll"")] public static extern int puts(string c);]@74", "Delete [(string c)]@134", "Delete [string c]@135"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "puts(string c)"))); } [Fact] public void MethodInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { void goo() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "void goo()", FeaturesResources.method)); } [Fact] public void PrivateMethodInsert() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { void goo() { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo() { }]@18", "Insert [()]@26"); edits.VerifyRudeDiagnostics(); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithParameters() { var src1 = @" using System; class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" using System; class C { void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo(int a) { }]@35", "Insert [(int a)]@43", "Insert [int a]@44"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.goo")) }); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithAttribute() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { [System.Obsolete] void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[System.Obsolete] void goo(int a) { }]@18", "Insert [(int a)]@49", "Insert [int a]@50"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodInsert_Virtual() { var src1 = @" class C { }"; var src2 = @" class C { public virtual void F() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public virtual void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Abstract() { var src1 = @" abstract class C { }"; var src2 = @" abstract class C { public abstract void F(); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public abstract void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Override() { var src1 = @" class C { }"; var src2 = @" class C { public override void F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public override void F()", FeaturesResources.method)); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void ExternMethodInsert() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[DllImport(""msvcrt.dll"")] private static extern int puts(string c);]@74", "Insert [(string c)]@135", "Insert [string c]@136"); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int puts(string c)", FeaturesResources.method)); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethodDeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; // TODO: The method does not need to be updated since there are no sequence points generated for it. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethod_Attribute_DeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] [Obsolete] private static extern int puts(string c); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodReorder1() { var src1 = "class C { void f(int a, int b) { a = b; } void g() { } }"; var src2 = "class C { void g() { } void f(int a, int b) { a = b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Reorder [void g() { }]@42 -> @10"); } [Fact] public void MethodInsertDelete1() { var src1 = "class C { class D { } void f(int a, int b) { a = b; } }"; var src2 = "class C { class D { void f(int a, int b) { a = b; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void f(int a, int b) { a = b; }]@20", "Insert [(int a, int b)]@26", "Insert [int a]@27", "Insert [int b]@34", "Delete [void f(int a, int b) { a = b; }]@22", "Delete [(int a, int b)]@28", "Delete [int a]@29", "Delete [int b]@36"); } [Fact] public void MethodUpdate_AddParameter() { var src1 = @" class C { static void Main() { } }"; var src2 = @" class C { static void Main(string[] args) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string[] args]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "string[] args", FeaturesResources.parameter)); } [Fact] public void MethodUpdate_UpdateParameter() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [string[] args]@35 -> [string[] b]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_UpdateParameterAndBody() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { System.Console.Write(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Method_Name_Update() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void EntryPoint(string[] args) { } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [static void Main(string[] args) { }]@18 -> [static void EntryPoint(string[] args) { }]@18"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "static void EntryPoint(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AsyncMethod0() { var src1 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(500); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AsyncMethod1() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; }]@151 -> [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; }]@151"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddReturnTypeAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [return: Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[return: Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute_SupportedByRuntime() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Test.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 4, 5, 6})] void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter_NoChange() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 1; } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddAttribute2() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute3() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute4() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete("""")] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodUpdate_DeleteAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute2() { var src1 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute3() { var src1 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_ExplicitlyImplemented1() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(2); } void J.Goo() { Console.WriteLine(1); } }"; var src2 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(2); }]@25 -> [void I.Goo() { Console.WriteLine(1); }]@25", "Update [void J.Goo() { Console.WriteLine(1); }]@69 -> [void J.Goo() { Console.WriteLine(2); }]@69"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_ExplicitlyImplemented2() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var src2 = @" class C : I, J { void Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(1); }]@25 -> [void Goo() { Console.WriteLine(1); }]@25"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "void Goo()", FeaturesResources.method)); } [WorkItem(754255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754255")] [Fact] public void MethodUpdate_UpdateStackAlloc() { var src1 = @" class C { static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } } }"; var src2 = @" class C { static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } } }"; var expectedEdit = @"Update [static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } }]@18 -> [static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } }]@18"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Theory] [InlineData("stackalloc int[3]")] [InlineData("stackalloc int[3] { 1, 2, 3 }")] [InlineData("stackalloc int[] { 1, 2, 3 }")] [InlineData("stackalloc[] { 1, 2, 3 }")] public void MethodUpdate_UpdateStackAlloc2(string stackallocDecl) { var src1 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 1; } }"; var src2 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda1() { var src1 = "unsafe class C { void M() { F(1, () => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, () => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda2() { var src1 = "unsafe class C { void M() { F(1, x => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, x => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInAnonymousMethod() { var src1 = "unsafe class C { void M() { F(1, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLocalFunction() { var src1 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(1); } }"; var src2 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda1() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda2() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLocalFunction() { var src1 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(1); } }"; var src2 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInQuery() { var src1 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 1; } }"; var src2 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_UpdateAnonymousMethod() { var src1 = "class C { void M() => F(1, delegate(int a) { return a; }); }"; var src2 = "class C { void M() => F(2, delegate(int a) { return a; }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Query() { var src1 = "class C { void M() { F(1, from goo in bar select baz); } }"; var src2 = "class C { void M() { F(2, from goo in bar select baz); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_Query() { var src1 = "class C { void M() => F(1, from goo in bar select baz); }"; var src2 = "class C { void M() => F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AnonymousType() { var src1 = "class C { void M() { F(1, new { A = 1, B = 2 }); } }"; var src2 = "class C { void M() { F(2, new { A = 1, B = 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_AnonymousType() { var src1 = "class C { void M() => F(new { A = 1, B = 2 }); }"; var src2 = "class C { void M() => F(new { A = 10, B = 20 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Iterator_YieldReturn() { var src1 = "class C { IEnumerable<int> M() { yield return 1; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AddYieldReturn() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void MethodUpdate_AddYieldReturn_NotSupported() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodIterator, "IEnumerable<int> M()")); } [Fact] public void MethodUpdate_Iterator_YieldBreak() { var src1 = "class C { IEnumerable<int> M() { F(); yield break; } }"; var src2 = "class C { IEnumerable<int> M() { G(); yield break; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [WorkItem(1087305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087305")] [Fact] public void MethodUpdate_LabeledStatement() { var src1 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(1); } } }"; var src2 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_LocalFunctionsParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { void f(ref int b) => b = 1; } }"; var src2 = @"class C { public void M(int a) { void f(out int b) => b = 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { void f(ref int b) => b = 1; }]@10 -> [public void M(int a) { void f(out int b) => b = 1; }]@10"); } [Fact] public void MethodUpdate_LambdaParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { f((ref int b) => b = 1); } }"; var src2 = @"class C { public void M(int a) { f((out int b) => b = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { f((ref int b) => b = 1); }]@10 -> [public void M(int a) { f((out int b) => b = 1); }]@10"); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int M(in int b) => throw null;]@13", "Insert [(in int b)]@18", "Insert [in int b]@19"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int M(int b) => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@19 -> [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int M() => throw null;]@13", "Insert [()]@31"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M() => throw null;]@13 -> [ref readonly int M() => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@345"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, "string IConflict.Get()", FeaturesResources.method)); } [Fact] public void Method_Partial_DeleteInsert_DefinitionPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { partial void F() { } }"; var srcC2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteInsert_ImplementationPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void Method_Partial_Swap_ImplementationAndDefinitionParts() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F() { } }"; var srcB2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteImplementation() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteInsertBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcD1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F(); }"; var srcD2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }) }); } [Fact] public void Method_Partial_Insert() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact] public void Method_Partial_Insert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } #endregion #region Operators [Theory] [InlineData("implicit", "explicit")] [InlineData("explicit", "implicit")] public void Operator_Modifiers_Update(string oldModifiers, string newModifiers) { var src1 = "class C { public static " + oldModifiers + " operator int (C c) => 0; }"; var src2 = "class C { public static " + newModifiers + " operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static " + oldModifiers + " operator int (C c) => 0;]@10 -> [public static " + newModifiers + " operator int (C c) => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static " + newModifiers + " operator int (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Modifiers_Update_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static implicit operator int (C c) => 0; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static explicit operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Operator_Conversion_ExternModifiers_Add() { var src1 = "class C { public static implicit operator bool (C c) => default; }"; var src2 = "class C { extern public static implicit operator bool (C c); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "extern public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Conversion_ExternModifiers_Remove() { var src1 = "class C { extern public static implicit operator bool (C c); }"; var src2 = "class C { public static implicit operator bool (C c) => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void OperatorInsert() { var src1 = @" class C { } "; var src2 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator), Diagnostic(RudeEditKind.InsertOperator, "public static C operator +(C c, C d)", FeaturesResources.operator_)); } [Fact] public void OperatorDelete() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(CSharpFeaturesResources.conversion_operator, "implicit operator bool(C c)")), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.operator_, "operator +(C c, C d)"))); } [Fact] public void OperatorInsertDelete() { var srcA1 = @" partial class C { public static implicit operator bool (C c) => false; } "; var srcB1 = @" partial class C { public static C operator +(C c, C d) => c; } "; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Addition")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Implicit")) }), }); } [Fact] public void OperatorUpdate() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { public static implicit operator bool (C c) { return true; } public static C operator +(C c, C d) { return d; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_Update() { var src1 = @" class C { public static implicit operator bool (C c) => false; public static C operator +(C c, C d) => c; } "; var src2 = @" class C { public static implicit operator bool (C c) => true; public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_ToBlockBody() { var src1 = "class C { public static C operator +(C c, C d) => d; }"; var src2 = "class C { public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) => d;]@10 -> [public static C operator +(C c, C d) { return c; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorWithBlockBody_ToExpressionBody() { var src1 = "class C { public static C operator +(C c, C d) { return c; } }"; var src2 = "class C { public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) { return c; }]@10 -> [public static C operator +(C c, C d) => d;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorReorder1() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static implicit operator int (C c) { return 1; } } "; var src2 = @" class C { public static implicit operator int (C c) { return 1; } public static implicit operator bool (C c) { return false; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static implicit operator int (C c) { return 1; }]@84 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void OperatorReorder2() { var src1 = @" class C { public static C operator +(C c, C d) { return c; } public static C operator -(C c, C d) { return d; } } "; var src2 = @" class C { public static C operator -(C c, C d) { return d; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static C operator -(C c, C d) { return d; }]@74 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Operator_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public static bool operator !(in Test b) => throw null;]@13", "Insert [(in Test b)]@42", "Insert [in Test b]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static bool operator !(in Test b)", FeaturesResources.operator_)); } [Fact] public void Operator_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { public static bool operator !(Test b) => throw null; }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Test b]@43 -> [in Test b]@43"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in Test b", FeaturesResources.parameter)); } #endregion #region Constructor, Destructor [Fact] public void Constructor_Parameter_AddAttribute() { var src1 = @" class C { private int x = 1; public C(int a) { } }"; var src2 = @" class C { private int x = 2; public C([System.Obsolete]int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [x = 1]@30 -> [x = 2]@30", "Update [int a]@53 -> [[System.Obsolete]int a]@53"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] [WorkItem(2068, "https://github.com/dotnet/roslyn/issues/2068")] public void Constructor_ExternModifier_Add() { var src1 = "class C { }"; var src2 = "class C { public extern C(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public extern C();]@10", "Insert [()]@25"); // This can be allowed as the compiler generates an empty constructor, but it's not worth the complexity. edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public extern C()", FeaturesResources.constructor)); } [Fact] public void ConstructorInitializer_Update1() { var src1 = @" class C { public C(int a) : base(a) { } }"; var src2 = @" class C { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@18 -> [public C(int a) : base(a + 1) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update2() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [Fact] public void ConstructorInitializer_Update3() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a) : base(a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) { }]@18 -> [public C(int a) : base(a) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update4() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) : base(a + 1) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [WorkItem(743552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743552")] [Fact] public void ConstructorUpdate_AddParameter() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a, int b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@26 -> [(int a, int b)]@26", "Insert [int b]@34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int b", FeaturesResources.parameter)); } [Fact] public void DestructorDelete() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { }"; var expectedEdit1 = @"Delete [~B() { }]@10"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit1); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] public void DestructorDelete_InsertConstructor() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { B() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [B() { }]@10", "Insert [()]@11", "Delete [~B() { }]@10"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "B()", FeaturesResources.constructor), Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] [WorkItem(789577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789577")] public void ConstructorUpdate_AnonymousTypeInFieldInitializer() { var src1 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 1; } }"; var src2 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_Static_Delete() { var src1 = "class C { static C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.static_constructor, "C()"))); } [Fact] public void Constructor_Static_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { static C() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Constructor_Static_Insert() { var src1 = "class C { }"; var src2 = "class C { static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void InstanceCtorDelete_Public() { var src1 = "class C { public C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("protected internal")] public void InstanceCtorDelete_NonPublic(string accessibility) { var src1 = "class C { [System.Obsolete] " + accessibility + " C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void InstanceCtorDelete_Public_PartialWithInitializerUpdate() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void InstanceCtorInsert_Public_Implicit() { var src1 = "class C { }"; var src2 = "class C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Partial_Public_Implicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // no change in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtorInsert_Public_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }); } [Fact] public void InstanceCtorInsert_Partial_Public_NoImplicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C(int a) { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { public C(int a) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }), // no change in document B DocumentResults(), }); } [Fact] public void InstanceCtorInsert_Private_Implicit1() { var src1 = "class C { }"; var src2 = "class C { private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Private_Implicit2() { var src1 = "class C { }"; var src2 = "class C { C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Protected_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "protected C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorUpdate_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Private_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C") .InstanceConstructors.Single(ctor => ctor.DeclaredAccessibility == Accessibility.Private)) }); } [Fact] public void InstanceCtorInsert_Internal_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_Protected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_InternalProtected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void StaticCtor_Partial_DeleteInsert() { var srcA1 = "partial class C { static C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { static C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPrivate() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePublicInsertPublic() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPublic() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be reported as rude edit in the other document where it was inserted back with changed accessibility DocumentResults( semanticEdits: NoSemanticEdits), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), }); } [Fact] public void StaticCtor_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { static C() { } }"; var srcA2 = "partial class C { static C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePublic() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPrivateDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { private C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_DeleteInternalInsertInternal() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeleteInternal_WithBody() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { Console.WriteLine(1); } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), // delete of the constructor in partial part will be reported as rude in the the other document where it was inserted with changed accessibility DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor) }), DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 2</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_Trivia1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); /*new trivia*/public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_ExplicitInterfaceImpl1() { var src1 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 1</N:0.3>); } } "; var src2 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 2</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_Parameterless_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO: //var syntaxMap = GetSyntaxMap(src1, src2); //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_WithParameters_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO: bug https://github.com/dotnet/roslyn/issues/2504 //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a <N:0.0>= 1</N:0.0>; C(uint arg) => Console.WriteLine(2); } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a <N:0.0>= 2</N:0.0>; // updated field initializer C(uint arg) => Console.WriteLine(2); C(byte arg) => Console.WriteLine(3); // new ctor } "; var syntaxMapB = GetSyntaxMap(srcB1, srcB2)[0]; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Int32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Boolean"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "UInt32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Byte"), syntaxMap: null), }) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update_SemanticError() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a = 1; } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a = 2; C(int arg) => Console.WriteLine(2); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), // The actual edits do not matter since there are semantic errors in the compilation. // We just should not crash. DocumentResults(diagnostics: Array.Empty<RudeEditDiagnosticDescription>()) }); } [Fact] public void InstanceCtor_Partial_Implicit_Update() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { int G = 1; }"; var srcA2 = "partial class C { int F = 2; }"; var srcB2 = "partial class C { int G = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void ParameterlessConstructor_SemanticError_Delete1() { var src1 = @" class C { D() {} } "; var src2 = @" class C { } "; var edits = GetTopEdits(src1, src2); // The compiler interprets D() as a constructor declaration. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void Constructor_SemanticError_Partial() { var src1 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(1); } } "; var src2 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("C").PartialImplementationPart) }); } [Fact] public void PartialDeclaration_Delete() { var srcA1 = "partial class C { public C() { } void F() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = ""; var srcB2 = "partial class C { int x = 2; void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert() { var srcA1 = ""; var srcB1 = "partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert_Reloadable() { var srcA1 = ""; var srcB1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_BlockBodyToExpressionBody() { var src1 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var src2 = @" public class C { private int _value; public C(int value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) { _value = value; }]@52 -> [public C(int value) => _value = value;]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_BlockBodyToExpressionBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) : base(value) { _value = value; }]@90 -> [public C(int value) : base(value) => _value = value;]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { private int _value; public C(int value) => _value = value; } "; var src2 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) => _value = value;]@52 -> [public C(int value) { _value = value; }]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_ExpressionBodyToBlockBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) : base(value) => _value = value;]@90 -> [public C(int value) : base(value) { _value = value; }]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_BlockBodyToExpressionBody() { var src1 = @" public class C { ~C() { Console.WriteLine(0); } } "; var src2 = @" public class C { ~C() => Console.WriteLine(0); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() { Console.WriteLine(0); }]@25 -> [~C() => Console.WriteLine(0);]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { ~C() => Console.WriteLine(0); } "; var src2 = @" public class C { ~C() { Console.WriteLine(0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() => Console.WriteLine(0);]@25 -> [~C() { Console.WriteLine(0); }]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [Test(in int b) => throw null;]@13", "Insert [(in int b)]@17", "Insert [in int b]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { Test() => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Constructor_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { Test(int b) => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@18 -> [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } #endregion #region Fields and Properties with Initializers [Fact] public void FieldInitializer_Update1() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update1() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get; } = 1;]@10"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializer_Update2() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializer_Update2() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get { return 1; } }]@10", "Update [get;]@18 -> [get { return 1; }]@18"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)); } [Fact] public void PropertyInitializer_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int a { get; } = 0; }"; var srcA2 = "partial class C { int a { get { return 1; } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults() }); } [Fact] public void FieldInitializer_Update3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update3() { var src1 = "class C { int a { get { return 1; } } }"; var src2 = "class C { int a { get; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get { return 1; } }]@10 -> [int a { get; } = 0;]@10", "Update [get { return 1; }]@18 -> [get;]@18"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21", "Delete [static C() { }]@24", "Delete [()]@32"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2;}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate_Private() { var src1 = "class C { int a; [System.Obsolete]C() { } }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate_Private() { var src1 = "class C { int a { get; } = 1; C() { } }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate_Public() { var src1 = "class C { int a; public C() { } }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate_Public() { var src1 = "class C { int a { get; } = 1; public C() { } }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate2() { var src1 = "class C { int a; public C() { } }"; var src2 = "class C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate2() { var src1 = "class C { int a { get; } = 1; public C() { } }"; var src2 = "class C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate4() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate6() { var src1 = "class C { int a; private C(int a) : this(true) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) : this(true) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertImplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertExplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [static C() { }]@28", "Insert [()]@36", "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorInsertExplicit() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorInsertExplicit() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_GenericType() { var src1 = "class C<T> { int a = 1; }"; var src2 = "class C<T> { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@17 -> [a = 2]@17"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "a = 2"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void PropertyInitializerUpdate_GenericType() { var src1 = "class C<T> { int a { get; } = 1; }"; var src2 = "class C<T> { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "int a"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void FieldInitializerUpdate_StackAllocInConstructor() { var src1 = "unsafe class C { int a = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@21 -> [a = 2]@21"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void FieldInitializerUpdate_SwitchExpressionInConstructor() { var src1 = "class C { int a = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor1() { var src1 = "unsafe class C { int a { get; } = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor2() { var src1 = "unsafe class C { int a { get; } = 1; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor3() { var src1 = "unsafe class C { int a { get; } = 1; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor1() { var src1 = "class C { int a { get; } = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor2() { var src1 = "class C { int a { get; } = 1; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var src2 = "class C { int a { get; } = 2; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor3() { var src1 = "class C { int a { get; } = 1; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@14 -> [a = 2]@14"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a { get; } = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a { get; } = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@33 -> [a = 2]@33"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a { get; } = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a { get; } = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a { get; } = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a { get; } = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a = 1; }"; var src2 = "partial class C { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a { get; } = 1; }"; var src2 = "partial class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a = 1; } partial class C { }"; var src2 = "partial class C { int a = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a { get; } = 1; } partial class C { }"; var src2 = "partial class C { int a { get; } = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a = F(1, (x, y) => x + y); }"; var src2 = "class C { int a = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a { get; } = F(1, (x, y) => x + y); }"; var src2 = "class C { int a { get; } = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_SimpleLambda() { var src1 = "class C { int a = F(1, x => x); }"; var src2 = "class C { int a = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_SimpleLambda() { var src1 = "class C { int a { get; } = F(1, x => x); }"; var src2 = "class C { int a { get; } = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Query() { var src1 = "class C { int a = F(1, from goo in bar select baz); }"; var src2 = "class C { int a = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_Query() { var src1 = "class C { int a { get; } = F(1, from goo in bar select baz); }"; var src2 = "class C { int a { get; } = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousType() { var src1 = "class C { int a = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousType() { var src1 = "class C { int a { get; } = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a { get; } = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) {} public C(bool b) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) {} public C(bool b) {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 2</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_EditConstructorNotIncludingInitializers() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_RemoveCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_AddCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_UpdateBaseCtorInitializerWithLambdas1() { var src1 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 1</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 2</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_PartialDeclarationDelete_SingleDocument() { var src1 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); } partial class C { public C() { } static int F(Func<int, int> x) => 1; } "; var src2 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); static int F(Func<int, int> x) => 1; } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), syntaxMap[0]), }); } [Fact] public void FieldInitializerUpdate_ActiveStatements1() { var src1 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 1; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 2; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); var activeStatements = GetActiveStatements(src1, src2); edits.VerifySemantics( activeStatements, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]), }); } [Fact] public void PropertyWithInitializer_SemanticError_Partial() { var src1 = @" partial class C { partial int P => 1; } partial class C { partial int P => 1; } "; var src2 = @" partial class C { partial int P => 1; } partial class C { partial int P => 2; public C() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => ((IPropertySymbol)c.GetMember<INamedTypeSymbol>("C").GetMembers("P").First()).GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Partial_DeleteInsert_InitializerRemoval() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void Field_Partial_DeleteInsert_InitializerUpdate() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } #endregion #region Fields [Fact] public void Field_Rename() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int b = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [b = 0]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "b = 0", FeaturesResources.field)); } [Fact] public void Field_Kind_Update() { var src1 = "class C { Action a; }"; var src2 = "class C { event Action a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Action a;]@10 -> [event Action a;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FieldKindUpdate, "event Action a", FeaturesResources.event_)); } [Theory] [InlineData("static")] [InlineData("volatile")] [InlineData("const")] public void Field_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F = 0; }"; var src2 = "class C { " + newModifiers + "int F = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F = 0;]@10 -> [" + newModifiers + "int F = 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F = 0", FeaturesResources.field)); } [Fact] public void Field_Modifier_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { static int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ModifiersUpdate, "F", FeaturesResources.field) }), DocumentResults(), }); } [Fact] public void Field_Attribute_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { [System.Obsolete]int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_FixedSize_Update() { var src1 = "struct S { public unsafe fixed byte a[1], b[2]; }"; var src2 = "struct S { public unsafe fixed byte a[2], b[3]; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a[1]]@36 -> [a[2]]@36", "Update [b[2]]@42 -> [b[3]]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "a[2]", FeaturesResources.field), Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "b[3]", FeaturesResources.field)); } [WorkItem(1120407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120407")] [Fact] public void Field_Const_Update() { var src1 = "class C { const int x = 0; }"; var src2 = "class C { const int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [x = 0]@20 -> [x = 1]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "x = 1", FeaturesResources.const_field)); } [Fact] public void Field_Event_VariableDeclarator_Update() { var src1 = "class C { event Action a; }"; var src2 = "class C { event Action a = () => { }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@23 -> [a = () => { }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_Reorder() { var src1 = "class C { int a = 0; int b = 1; int c = 2; }"; var src2 = "class C { int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int c = 2", FeaturesResources.field)); } [Fact] public void Field_Insert() { var src1 = "class C { }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a = 1;]@10", "Insert [int a = 1]@10", "Insert [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Insert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { this = default(S); a = z; } } "; var src2 = @" struct S { public int a; private int b; private static int c; private static int f = 1; private event System.Action d; public S(int z) { this = default(S); a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "b", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "c", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "f = 1", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "d", CSharpFeaturesResources.event_field, CSharpFeaturesResources.struct_)); } [Fact] public void Field_Insert_IntoLayoutClass_Auto() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.b")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.c")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.d")), }); } [Fact] public void Field_Insert_IntoLayoutClass_Explicit() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; [FieldOffset(0)] private int b; [FieldOffset(4)] private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void Field_Insert_ConstructorReplacingImplicitConstructor_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() // new ctor replacing existing implicit constructor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ParameterlessConstructorInsert_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersButNoExistingLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single()) }); } [Fact] public void Field_Insert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddStaticFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Insert_Static_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public static int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddInstanceFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add_NotSupportedByRuntime() { var src1 = @" class C { public int a = 1, x = 1; }"; var src2 = @" class C { [System.Obsolete]public int a = 1, x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public int a = 1, x = 1;]@18 -> [[System.Obsolete]public int a = 1, x = 1;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add() { var src1 = @" class C { public int a, b; }"; var src2 = @" class C { [System.Obsolete]public int a, b; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.b")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_Add_WithInitializer() { var src1 = @" class C { int a; }"; var src2 = @" class C { [System.Obsolete]int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_DeleteInsertUpdate_WithInitializer() { var srcA1 = "partial class C { int a = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { [System.Obsolete]int a = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Delete1() { var src1 = "class C { int a = 1; }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a = 1;]@10", "Delete [int a = 1]@10", "Delete [a = 1]@14"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void Field_UnsafeModifier_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node* left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [unsafe Node* left;]@14 -> [Node* left;]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_ModifierAndType_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe Node* left;]@14 -> [Node left;]@14", "Update [Node* left]@21 -> [Node left]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "Node left", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Event_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Event_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_), Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_)); } [Fact] public void Field_Type_Update_ReorderRemoveAdd() { var src1 = "class C { int F, G, H; bool U; }"; var src2 = "class C { string G, F; double V, U; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int F, G, H]@10 -> [string G, F]@10", "Reorder [G]@17 -> @17", "Update [bool U]@23 -> [double V, U]@23", "Insert [V]@30", "Delete [H]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "double V, U", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "string G, F", DeletedSymbolDisplay(FeaturesResources.field, "H"))); } [Fact] public void Field_Event_Reorder() { var src1 = "class C { int a = 0; int b = 1; event int c = 2; }"; var src2 = "class C { event int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "event int c = 2", CSharpFeaturesResources.event_field)); } [Fact] public void Field_Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E = 2; }"; var srcA2 = "partial class C { event int E = 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } #endregion #region Properties [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Property_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F => 0; }"; var src2 = "class C { " + newModifiers + "int F => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F => 0;]@10 -> [" + newModifiers + "int F => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Rename() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int Q => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Update() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [int P => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Property_ExpressionBody_ModifierUpdate() { var src1 = "class C { int P => 1; }"; var src2 = "class C { unsafe int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [unsafe int P => 1;]@10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ExpressionBodyToBlockBody1() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } }]@10", "Insert [{ get { return 2; } }]@16", "Insert [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_ExpressionBodyToBlockBody2() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } set { } }]@10", "Insert [{ get { return 2; } set { } }]@16", "Insert [get { return 2; }]@18", "Insert [set { }]@36"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody1() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } }]@16", "Delete [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody2() { var src1 = "class C { int P { get { return 2; } set { } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } set { } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } set { } }]@16", "Delete [get { return 2; }]@18", "Delete [set { }]@36"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get => 2; }]@10", "Insert [{ get => 2; }]@16", "Insert [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get => 2; }]@10 -> [int P => 1;]@10", "Delete [{ get => 2; }]@16", "Delete [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int P { set { } } }"; var src2 = "class C { int P { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@18 -> [set => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int P { init { } } }"; var src2 = "class C { int P { init => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@18 -> [init => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod, preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyWithSetterToGetterExpressionBodyWithSetter() { var src1 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyWithSetterToGetterBlockBodyWithSetter() { var src1 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_Rename1() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_Rename2() { var src1 = "class C { int I.P { get { return 1; } } }"; var src2 = "class C { int J.P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.P", FeaturesResources.property_)); } [Fact] public void Property_RenameAndUpdate() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyDelete() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.property_, "P"))); } [Fact] public void PropertyReorder1() { var src1 = "class C { int P { get { return 1; } } int Q { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get { return 1; } }]@38 -> @10"); // TODO: we can allow the move since the property doesn't have a backing field edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyReorder2() { var src1 = "class C { int P { get; set; } int Q { get; set; } }"; var src2 = "class C { int Q { get; set; } int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get; set; }]@30 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.auto_property)); } [Fact] public void PropertyAccessorReorder_GetSet() { var src1 = "class C { int P { get { return 1; } set { } } }"; var src2 = "class C { int P { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyAccessorReorder_GetInit() { var src1 = "class C { int P { get { return 1; } init { } } }"; var src2 = "class C { int P { init { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [init { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyTypeUpdate() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { char P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; set; }]@10 -> [char P { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "char P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "get", CSharpFeaturesResources.property_getter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyInsert() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("P"))); } [Fact] public void PropertyInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "int P", FeaturesResources.auto_property)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void PropertyInsert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { private static extern int P1 { [DllImport(""x.dll"")]get; } private static extern int P2 { [DllImport(""x.dll"")]set; } private static extern int P3 { [DllImport(""x.dll"")]get; [DllImport(""x.dll"")]set; } } "; var edits = GetTopEdits(src1, src2); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int P1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P3", FeaturesResources.property_)); } [Fact] public void PropertyInsert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { a = z; } } "; var src2 = @" struct S { public int a; private static int c { get; set; } private static int e { get { return 0; } set { } } private static int g { get; } = 1; private static int i { get; set; } = 1; private static int k => 1; public S(int z) { a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "private static int c { get; set; }", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int g { get; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_)); } [Fact] public void PropertyInsert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b { get; set; } private static int c { get; set; } private int d { get { return 0; } set { } } private static int e { get { return 0; } set { } } private int f { get; } = 1; private static int g { get; } = 1; private int h { get; set; } = 1; private static int i { get; set; } = 1; private int j => 1; private static int k => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int b { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int c { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int f { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int g { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int h { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_)); } // Design: Adding private accessors should also be allowed since we now allow adding private methods // and adding public properties and/or public accessors are not allowed. [Fact] public void PrivateProperty_AccessorAdd() { var src1 = "class C { int _p; int P { get { return 1; } } }"; var src2 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivatePropertyAccessorDelete() { var src1 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var src2 = "class C { int _p; int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorAdd1() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd2() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; private set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [private set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd4() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd5() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; internal set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [internal set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd6() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd_Init() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; init; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [init;]@23"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivateAutoPropertyAccessorDelete_Get() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_getter, "P.get"))); } [Fact] public void AutoPropertyAccessor_SetToInit() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set;]@23 -> [init;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "init", CSharpFeaturesResources.property_setter)); } [Fact] public void AutoPropertyAccessor_InitToSet() { var src1 = "class C { int P { get; init; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init;]@23 -> [set;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PrivateAutoPropertyAccessorDelete_Set() { var src1 = "class C { int P { get; set; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorDelete_Init() { var src1 = "class C { int P { get; init; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [init;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.init"))); } [Fact] public void AutoPropertyAccessorUpdate() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get;]@18 -> [set;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [WorkItem(992578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992578")] [Fact] public void InsertIncompleteProperty() { var src1 = "class C { }"; var src2 = "class C { public int P { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public int P { }]@10", "Insert [{ }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int P { get; }]@13", "Insert [{ get; }]@32", "Insert [get;]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Update() { var src1 = "class Test { int P { get; } }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; }]@13 -> [ref readonly int P { get; }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int P", FeaturesResources.property_)); } [Fact] public void Property_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get => 1; set { } } }"; var srcA2 = "partial class C { int P { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }), DocumentResults(), }); } [Fact] public void PropertyInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int Q { get => 1; init { } }}"; var srcA2 = "partial class C { int Q { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcA2 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod), }), DocumentResults(), }); } [Fact] public void AutoPropertyWithInitializer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } = 1; }"; var srcA2 = "partial class C { int P { get; set; } = 1; }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } [Fact] public void PropertyWithExpressionBody_Partial_InsertDeleteUpdate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P => 1; }"; var srcA2 = "partial class C { int P => 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_ReadOnly_Add() { var src1 = @" struct S { int P { get; } }"; var src2 = @" struct S { readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Property_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P1", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.property_setter)); } [Fact] public void Property_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P3").SetMethod, preserveLocalVariables: false) }); } #endregion #region Indexers [Theory] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Indexer_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int this[int a] => 0; }"; var src2 = "class C { " + newModifiers + "int this[int a] => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int this[int a] => 0;]@10 -> [" + newModifiers + "int this[int a] => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int this[int a]", FeaturesResources.indexer_)); } [Fact] public void Indexer_GetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [get { return 1; }]@28 -> [get { return 2; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_SetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set { System.Console.WriteLine(value); }]@46 -> [set { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_InitUpdate() { var src1 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init { System.Console.WriteLine(value); }]@46 -> [init { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void IndexerWithExpressionBody_Update() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)() + 10; } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)() + 11; // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)() + 10;]@35 -> [int this[int a] => new Func<int>(() => 2)() + 11;]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_2() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)();]@35 -> [int this[int a] => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_3() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(() => { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_4() { var src1 = @" using System; class C { int this[int a] => new Func<int>(delegate { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(delegate { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(delegate { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(delegate { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } }]@10", "Insert [{ get { return 1; } }]@26", "Insert [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } }]@26", "Delete [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get => 1; }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get => 1; }]@26", "Delete [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get => 1; }]@10", "Insert [{ get => 1; }]@26", "Insert [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int this[int a] { set { } } void F() { } }"; var src2 = "class C { int this[int a] { set => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@28 -> [set => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int this[int a] { init { } } void F() { } }"; var src2 = "class C { int this[int a] { init => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@28 -> [init => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterAndSetterBlockBodiesToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Delete [get { return 1; }]@28", "Delete [set { Console.WriteLine(0); }]@46"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterAndSetterBlockBodies() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10", "Insert [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Insert [get { return 1; }]@28", "Insert [set { Console.WriteLine(0); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_Rename() { var src1 = "class C { int I.this[int a] { get { return 1; } } }"; var src2 = "class C { int J.this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Indexer_Reorder1() { var src1 = "class C { int this[int a] { get { return 1; } } int this[string a] { get { return 1; } } }"; var src2 = "class C { int this[string a] { get { return 1; } } int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int this[string a] { get { return 1; } }]@48 -> @10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_AccessorReorder() { var src1 = "class C { int this[int a] { get { return 1; } set { } } }"; var src2 = "class C { int this[int a] { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@46 -> @28"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_TypeUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { string this[int a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get; set; }]@10 -> [string this[int a] { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Tuple_TypeUpdate() { var src1 = "class C { (int, int) M() { throw new System.Exception(); } }"; var src2 = "class C { (string, int) M() { throw new System.Exception(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { throw new System.Exception(); }]@10 -> [(string, int) M() { throw new System.Exception(); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(string, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementDelete() { var src1 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var src2 = "class C { (int, int) M() { return (1, 2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int, int a) M() { return (1, 2, 3); }]@10 -> [(int, int) M() { return (1, 2); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementAdd() { var src1 = "class C { (int, int) M() { return (1, 2); } }"; var src2 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { return (1, 2); }]@10 -> [(int, int, int a) M() { return (1, 2, 3); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int, int a) M()", FeaturesResources.method)); } [Fact] public void Indexer_ParameterUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { int this[string a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string a", FeaturesResources.parameter)); } [Fact] public void Indexer_AddGetAccessor() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [get { return arr[i]; }]@304"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "get", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_AddSetAccessor() { var src1 = @" class C { public int this[int i] { get { return default; } } }"; var src2 = @" class C { public int this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@67"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)); } [Fact] public void Indexer_AddSetAccessor_GenericType() { var src1 = @" class C<T> { public T this[int i] { get { return default; } } }"; var src2 = @" class C<T> { public T this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@68"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "set", CSharpFeaturesResources.indexer_setter)); } [WorkItem(750109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750109")] [Fact] public void Indexer_DeleteGetAccessor() { var src1 = @" class C<T> { public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var src2 = @" class C<T> { public T this[int i] { set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get { return arr[i]; }]@58"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public T this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_getter, "this[int i].get"))); } [Fact] public void Indexer_DeleteSetAccessor() { var src1 = @" class C { public int this[int i] { get { return 0; } set { } } }"; var src2 = @" class C { public int this[int i] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { }]@61"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public int this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int i].set"))); } [Fact, WorkItem(1174850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174850")] public void Indexer_Insert() { var src1 = "struct C { }"; var src2 = "struct C { public int this[int x, int y] { get { return x + y; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int this[in int i] => throw null;]@13", "Insert [[in int i]]@21", "Insert [in int i]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int i]@22 -> [in int i]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int i", FeaturesResources.parameter)); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int this[int i] => throw null;]@13", "Insert [[int i]]@34", "Insert [int i]@35"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int i] => throw null;]@13 -> [ref readonly int this[int i] => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int this[int i]", FeaturesResources.indexer_)); } [Fact] public void Indexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcA2 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void IndexerInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcA2 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoIndexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get; set; } }"; var srcA2 = "partial class C { int this[int x] { get; set; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod), }), DocumentResults(), }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Partial_InsertDeleteUpdate_LiftedParameter() { var srcA1 = @" partial class C { }"; var srcB1 = @" partial class C { int this[int a] => new System.Func<int>(() => a + 1); }"; var srcA2 = @" partial class C { int this[int a] => new System.Func<int>(() => 2); // no capture }"; var srcB2 = @" partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a") }), DocumentResults(), }); } [Fact] public void AutoIndexer_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get; } }"; var src2 = @" struct S { readonly int this[int x] { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.indexer_setter)); } [Fact] public void Indexer_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "UInt32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false) }); } #endregion #region Events [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Event_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "event Action F { add {} remove {} } }"; var src2 = "class C { " + newModifiers + "event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "event Action F { add {} remove {} }]@10 -> [" + newModifiers + "event Action F { add {} remove {} }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "event Action F", FeaturesResources.event_)); } [Fact] public void Event_Accessor_Reorder1() { var src1 = "class C { event int E { add { } remove { } } }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [remove { }]@32 -> @24"); edits.VerifyRudeDiagnostics(); } [Fact] public void Event_Accessor_Reorder2() { var src1 = "class C { event int E1 { add { } remove { } } event int E1 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E2 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event int E1 { add { } remove { } }]@10 -> [event int E2 { remove { } add { } }]@10", "Update [event int E1 { add { } remove { } }]@49 -> [event int E2 { remove { } add { } }]@49", "Reorder [remove { }]@33 -> @25", "Reorder [remove { }]@72 -> @64"); } [Fact] public void Event_Accessor_Reorder3() { var src1 = "class C { event int E1 { add { } remove { } } event int E2 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E1 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int E2 { add { } remove { } }]@49 -> @10", "Reorder [remove { }]@72 -> @25", "Reorder [remove { }]@33 -> @64"); } [Fact] public void Event_Insert() { var src1 = "class C { }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("E"))); } [Fact] public void Event_Delete() { var src1 = "class C { event int E { remove { } add { } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.event_, "E"))); } [Fact] public void Event_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { } "; var src2 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private event Action c { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_ExpressionBodyToBlockBody() { var src1 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add => F();]@57 -> [add { F(); }]@56", "Update [remove => F();]@69 -> [remove { }]@69" ); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_BlockBodyToExpressionBody() { var src1 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var src2 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add { F(); }]@56 -> [add => F();]@57", "Update [remove { }]@69 -> [remove => F();]@69" ); edits.VerifySemanticDiagnostics(); } [Fact] public void Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E { add { } remove { } } }"; var srcA2 = "partial class C { event int E { add { } remove { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod) }), DocumentResults(), }); } [Fact] public void Event_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { public event Action E { add {} remove {} } }"; var src2 = @" struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly event Action E", FeaturesResources.event_)); } [Fact] public void Event_InReadOnlyStruct_ReadOnly_Add1() { var src1 = @" readonly struct S { public event Action E { add {} remove {} } }"; var src2 = @" readonly struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough bodies nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").RemoveMethod)); } [Fact] public void Field_Event_Attribute_Add() { var src1 = @" class C { event Action F; }"; var src2 = @" class C { [System.Obsolete]event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F;]@18 -> [[System.Obsolete]event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F { add {} remove {} }]@18 -> [[System.Obsolete]event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [remove {}]@42 -> [[System.Obsolete]remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F; }"; var src2 = @" class C { event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F;]@18 -> [event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F { add {} remove {} }]@18 -> [event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Delete() { var src1 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]remove {}]@42 -> [remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Parameter [Fact] public void ParameterRename_Method1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterRename_Ctor1() { var src1 = @"class C { public C(int a) {} }"; var src2 = @"class C { public C(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@19 -> [int b]@19"); } [Fact] public void ParameterRename_Operator1() { var src1 = @"class C { public static implicit operator int(C a) {} }"; var src2 = @"class C { public static implicit operator int(C b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C a]@46 -> [C b]@46"); } [Fact] public void ParameterRename_Operator2() { var src1 = @"class C { public static int operator +(C a, C b) { return 0; } }"; var src2 = @"class C { public static int operator +(C a, C x) { return 0; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C b]@44 -> [C x]@44"); } [Fact] public void ParameterRename_Indexer2() { var src1 = @"class C { public int this[int a, int b] { get { return 0; } } }"; var src2 = @"class C { public int this[int a, int x] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@33 -> [int x]@33"); } [Fact] public void ParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@24"); } [Fact] public void ParameterInsert2() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int a, ref int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@23 -> [(int a, ref int b)]@23", "Insert [ref int b]@31"); } [Fact] public void ParameterDelete1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@24"); } [Fact] public void ParameterDelete2() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b)]@23 -> [(int b)]@23", "Delete [int a]@24"); } [Fact] public void ParameterUpdate() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterReorder() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24"); } [Fact] public void ParameterReorderAndUpdate() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int c) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24", "Update [int a]@24 -> [int c]@31"); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Parameter_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Parameter_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " a", FeaturesResources.parameter)); } [Fact] public void Parameter_Type_Nullable() { var src1 = @" #nullable enable class C { static void M(string a) { } } "; var src2 = @" #nullable disable class C { static void M(string a) { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("this")] [InlineData("ref")] [InlineData("out")] [InlineData("params")] public void Parameter_Modifier_Remove(string modifier) { var src1 = @"static class C { static void F(" + modifier + " int[] a) { } }"; var src2 = @"static class C { static void F(int[] a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "int[] a", FeaturesResources.parameter)); } [Theory] [InlineData("int a = 1", "int a = 2")] [InlineData("int a = 1", "int a")] [InlineData("int a", "int a = 2")] [InlineData("object a = null", "object a")] [InlineData("object a", "object a = null")] [InlineData("double a = double.NaN", "double a = 1.2")] public void Parameter_Initializer_Update(string oldParameter, string newParameter) { var src1 = @"static class C { static void F(" + oldParameter + ") { } }"; var src2 = @"static class C { static void F(" + newParameter + ") { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, newParameter, FeaturesResources.parameter)); } [Fact] public void Parameter_Initializer_NaN() { var src1 = @"static class C { static void F(double a = System.Double.NaN) { } }"; var src2 = @"static class C { static void F(double a = double.NaN) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Parameter_Initializer_InsertDeleteUpdate() { var srcA1 = @"partial class C { }"; var srcB1 = @"partial class C { public static void F(int x = 1) {} }"; var srcA2 = @"partial class C { public static void F(int x = 2) {} }"; var srcB2 = @"partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(), }); } [Fact] public void Parameter_Attribute_Insert() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@63 -> [[A]int a]@63"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_NonCustomAttribute() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M([System.Runtime.InteropServices.InAttribute]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [[System.Runtime.InteropServices.InAttribute]int a]@24"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute1() { var attribute = "public class AAttribute : System.Security.Permissions.SecurityAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@101 -> [[A]int a]@101"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute2() { var attribute = "public class BAttribute : System.Security.Permissions.SecurityAttribute { }\n\n" + "public class AAttribute : BAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@143 -> [[A]int a]@143"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@72 -> [[A]int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M([A, B]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@120 -> [[A, B]int a]@120"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Delete_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@72 -> [int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([System.Obsolete(""1""), B]int a) {} }"; var src2 = attribute + @"class C { public void M([System.Obsolete(""2""), A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]int a]@120 -> [[System.Obsolete(\"2\"), A]int a]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) {} }"; var src2 = attribute + "class C { void F([A(1)]int a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) { F(0); } }"; var src2 = attribute + "class C { void F([A(1)]int a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F([A(0)]int a) { F(0); }]@60 -> [void F([A(1)]int a) { F(1); }]@60", "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Method Type Parameter [Fact] public void MethodTypeParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M<A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@23", "Insert [A]@24"); } [Fact] public void MethodTypeParameterInsert2() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<A,B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@23 -> [<A,B>]@23", "Insert [B]@26"); } [Fact] public void MethodTypeParameterDelete1() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterDelete2() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@23 -> [<B>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterUpdate() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@24 -> [B]@24"); } [Fact] public void MethodTypeParameterReorder() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24"); } [Fact] public void MethodTypeParameterReorderAndUpdate() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,C>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24", "Update [A]@24 -> [C]@26"); } [Fact] public void MethodTypeParameter_Attribute_Insert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<T>() {} }"; var src2 = attribute + @"class C { public void M<[A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@72 -> [[A]T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Insert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<[A, B]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@120 -> [[A, B]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@72 -> [T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[System.Obsolete(""1""), B]T>() {} }"; var src2 = attribute + @"class C { public void M<[System.Obsolete(""2""), A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@120 -> [[System.Obsolete(\"2\"), A]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) {} }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) { F(0); } }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F<[A(0)]T>(T a) { F(0); }]@60 -> [void F<[A(1)]T>(T a) { F(1); }]@60", "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<[A(1)]T>(T a)"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } #endregion #region Type Type Parameter [Fact] public void TypeTypeParameterInsert1() { var src1 = @"class C {}"; var src2 = @"class C<A> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@7", "Insert [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "A", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterInsert2() { var src1 = @"class C<A> {}"; var src2 = @"class C<A,B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@7 -> [<A,B>]@7", "Insert [B]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterDelete1() { var src1 = @"class C<A> { }"; var src2 = @"class C { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@7", "Delete [A]@8"); } [Fact] public void TypeTypeParameterDelete2() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@7 -> [<B>]@7", "Delete [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<B>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "A"))); } [Fact] public void TypeTypeParameterUpdate() { var src1 = @"class C<A> {}"; var src2 = @"class C<B> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@8 -> [B]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "B")); } [Fact] public void TypeTypeParameterReorder() { var src1 = @"class C<A,B> { }"; var src2 = @"class C<B,A> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterReorderAndUpdate() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B,C> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8", "Update [A]@8 -> [C]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.Renamed, "C", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "C")); } [Fact] public void TypeTypeParameterAttributeInsert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<[A, B]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@104 -> [[A, B]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert_SupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeDelete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@56 -> [T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeUpdate() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[System.Obsolete(""1""), B]T> {}"; var src2 = attribute + @"class C<[System.Obsolete(""2""), A]T> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@104 -> [[System.Obsolete(\"2\"), A]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple_Reloadable() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Type Parameter Constraints [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Insert(string newConstraint) { var src1 = "class C<S,T> { }"; var src2 = "class C<S,T> where T : " + newConstraint + " { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where T : " + newConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : " + newConstraint, FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : " + newConstraint)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Delete(string oldConstraint) { var src1 = "class C<S,T> where T : " + oldConstraint + " { }"; var src2 = "class C<S,T> { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where T : " + oldConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Theory] [InlineData("string", "string?")] [InlineData("(int a, int b)", "(int a, int c)")] public void TypeConstraint_Update_RuntimeTypeUnchanged(string oldType, string newType) { // note: dynamic is not allowed in constraints var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void TypeConstraint_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : System.Collections.Generic.List<" + newType + ">", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Fact] public void TypeConstraint_Delete_WithParameter() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S> where S : new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<S>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void TypeConstraint_MultipleClauses_Insert() { var src1 = "class C<S,T> where T : class { }"; var src2 = "class C<S,T> where S : unmanaged where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where S : unmanaged]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where S : unmanaged", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : unmanaged")); } [Fact] public void TypeConstraint_MultipleClauses_Delete() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S,T> where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where S : new()]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void TypeConstraint_MultipleClauses_Reorder() { var src1 = "class C<S,T> where S : struct where T : class { }"; var src2 = "class C<S,T> where T : class where S : struct { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@30 -> @13"); edits.VerifyRudeDiagnostics(); } [Fact] public void TypeConstraint_MultipleClauses_UpdateAndReorder() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<T,S> where T : class, I where S : class, new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@29 -> @13", "Reorder [T]@10 -> @8", "Update [where T : class]@29 -> [where T : class, I]@13", "Update [where S : new()]@13 -> [where S : class, new()]@32"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingConstraints, "where T : class, I", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : class, I"), Diagnostic(RudeEditKind.ChangingConstraints, "where S : class, new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : class, new()")); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_Update() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_InsertAndUpdate() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); Console.WriteLine(""What is your name?""); var name = Console.ReadLine(); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19", "Insert [Console.WriteLine(\"What is your name?\");]@54", "Insert [var name = Console.ReadLine();]@96"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_NoImplicitMain() { var src1 = @" using System; "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Delete_NoImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello World""); "; var src2 = @" using System; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"Hello World\");]@19"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_Delete_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var src2 = @" using System; Console.WriteLine(""Hello""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_StackAlloc() { var src1 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(1); }"; var src2 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_VoidToInt1() { var src1 = @" using System; Console.Write(1); "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt2() { var src1 = @" using System; Console.Write(1); return; "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt3() { var src1 = @" using System; Console.Write(1); int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_AddAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_DeleteAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_VoidToTask() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "await Task.Delay(100);")); } [Fact] public void TopLevelStatements_TaskToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return await GetInt();")); } [Fact] public void TopLevelStatements_IntToVoid1() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_IntToVoid2() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); return; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return;")); } [Fact] public void TopLevelStatements_IntToVoid3() { var src1 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "int Goo()\r\n{\r\n return 1;\r\n}")); } [Fact] public void TopLevelStatements_IntToVoid4() { var src1 = @" using System; Console.Write(1); return 1; public class C { public int Goo() { return 1; } } "; var src2 = @" using System; Console.Write(1); public class C { public int Goo() { return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskToVoid() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_TaskIntToTask() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskIntToVoid() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_WithLambda_Insert() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Update() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(2); public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Delete() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_UpdateMultiple() { var src1 = @" using System; Console.WriteLine(1); Console.WriteLine(2); public class C { } "; var src2 = @" using System; Console.WriteLine(3); Console.WriteLine(4); public class C { } "; var edits = GetTopEdits(src1, src2); // Since each individual statement is a separate update to a separate node, this just validates we correctly // only analyze the things once edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_MoveToOtherFile() { var srcA1 = @" using System; Console.WriteLine(1); public class A { }"; var srcB1 = @" using System; public class B { }"; var srcA2 = @" using System; public class A { }"; var srcB2 = @" using System; Console.WriteLine(2); public class B { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new [] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")) }), }); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class TopLevelEditingTests : EditingTestBase { #region Usings [Fact] public void Using_Global_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" global using D = System.Diagnostics; global using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [global using D = System.Diagnostics;]@2", "Insert [global using System.Collections;]@40"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Delete1() { var src1 = @" using System.Diagnostics; "; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using System.Diagnostics;]@2"); Assert.IsType<UsingDirectiveSyntax>(edits.Edits.First().OldNode); Assert.Null(edits.Edits.First().NewNode); } [Fact] public void Using_Delete2() { var src1 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [using D = System.Diagnostics;]@2", "Delete [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using D = System.Diagnostics;]@2", "Insert [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Collections;]@29 -> [using X = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update2() { var src1 = @" using System.Diagnostics; using X1 = System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X2 = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using X1 = System.Collections;]@29 -> [using X2 = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update3() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Diagnostics;]@2 -> [using System;]@2"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Reorder1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections; using System.Collections.Generic; using System.Diagnostics; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [using System.Diagnostics;]@2 -> @64"); } [Fact] public void Using_InsertDelete1() { var src1 = @" namespace N { using System.Collections; } namespace M { } "; var src2 = @" namespace N { } namespace M { using System.Collections; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@43", "Delete [using System.Collections;]@22"); } [Fact] public void Using_InsertDelete2() { var src1 = @" namespace N { using System.Collections; } "; var src2 = @" using System.Collections; namespace N { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@2", "Delete [using System.Collections;]@22"); } [Fact] public void Using_Delete_ChangesCodeMeaning() { // This test specifically validates the scenario we _don't_ support, namely when inserting or deleting // a using directive, if existing code changes in meaning as a result, we don't issue edits for that code. // If this ever regresses then please buy a lottery ticket because the feature has magically fixed itself. var src1 = @" using System.IO; using DirectoryInfo = N.C; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var src2 = @" using System.IO; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using DirectoryInfo = N.C;]@20"); edits.VerifySemantics(); } [Fact] public void Using_Insert_ForNewCode() { // As distinct from the above, this test validates a real world scenario of inserting a using directive // and changing code that utilizes the new directive to some effect. var src1 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var src2 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Delete_ForOldCode() { var src1 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var src2 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Insert_CreatesAmbiguousCode() { // This test validates that we still issue edits for changed valid code, even when unchanged // code has ambiguities after adding a using. var src1 = @" using System.Threading; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } } }"; var src2 = @" using System.Threading; using System.Timers; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } void M2() { // TimersDescriptionAttribute only exists in System.Timers System.Console.WriteLine(new TimersDescriptionAttribute("""")); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("N.C.M2"))); } #endregion #region Extern Alias [Fact] public void ExternAliasUpdate() { var src1 = "extern alias X;"; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [extern alias X;]@0 -> [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasInsert() { var src1 = ""; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasDelete() { var src1 = "extern alias Y;"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.extern_alias)); } #endregion #region Assembly/Module Attributes [Fact] public void Insert_TopLevelAttribute() { var src1 = ""; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [[assembly: System.Obsolete(\"2\")]]@0", "Insert [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "[assembly: System.Obsolete(\"2\")]", FeaturesResources.attribute)); } [Fact] public void Delete_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"2\")]"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [[assembly: System.Obsolete(\"2\")]]@0", "Delete [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.attribute)); } [Fact] public void Update_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")]"; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[assembly: System.Obsolete(\"1\")]]@0 -> [[assembly: System.Obsolete(\"2\")]]@0", "Update [System.Obsolete(\"1\")]@11 -> [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "System.Obsolete(\"2\")", FeaturesResources.attribute)); } [Fact] public void Reorder_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")][assembly: System.Obsolete(\"2\")]"; var src2 = "[assembly: System.Obsolete(\"2\")][assembly: System.Obsolete(\"1\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [[assembly: System.Obsolete(\"2\")]]@32 -> @0"); edits.VerifyRudeDiagnostics(); } #endregion #region Types [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 public void Type_Kind_Update(string oldKeyword, string newKeyword) { var src1 = oldKeyword + " C { }"; var src2 = newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + oldKeyword + " C { }]@0 -> [" + newKeyword + " C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeKindUpdate, newKeyword + " C")); } [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] public void Type_Kind_Update_Reloadable(string oldKeyword, string newKeyword) { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }]@145 -> [[CreateNewOnMetadataUpdate]" + newKeyword + " C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Modifiers_Static_Remove() { var src1 = "public static class C { }"; var src2 = "public class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public static class C { }]@0 -> [public class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public class C", FeaturesResources.class_)); } [Theory] [InlineData("public")] [InlineData("protected")] [InlineData("private")] [InlineData("private protected")] [InlineData("internal protected")] public void Type_Modifiers_Accessibility_Change(string accessibility) { var src1 = accessibility + " class C { }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + accessibility + " class C { }]@0 -> [class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", FeaturesResources.class_)); } [Theory] [InlineData("public", "public")] [InlineData("internal", "internal")] [InlineData("", "internal")] [InlineData("internal", "")] [InlineData("protected", "protected")] [InlineData("private", "private")] [InlineData("private protected", "private protected")] [InlineData("internal protected", "internal protected")] public void Type_Modifiers_Accessibility_Partial(string accessibilityA, string accessibilityB) { var srcA1 = accessibilityA + " partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = accessibilityB + " partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(), }); } [Fact] public void Type_Modifiers_Internal_Remove() { var src1 = "internal interface C { }"; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Internal_Add() { var src1 = "struct C { }"; var src2 = "internal struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Accessibility_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]public class C { }]@145 -> [[CreateNewOnMetadataUpdate]internal class C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInInterface_Remove(string keyword) { var src1 = "interface C { private " + keyword + " S { } }"; var src2 = "interface C { " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, keyword + " S", GetResource(keyword))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInClass_Add(string keyword) { var src1 = "class C { " + keyword + " S { } }"; var src2 = "class C { private " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPublicInInterface_Add(string keyword) { var src1 = "interface C { " + keyword + " S { } }"; var src2 = "interface C { public " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Add() { var src1 = "public class C { }"; var src2 = "public unsafe class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public class C { }]@0 -> [public unsafe class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Remove() { var src1 = @" using System; unsafe delegate void D(); class C { unsafe class N { } public unsafe event Action<int> A { add { } remove { } } unsafe int F() => 0; unsafe int X; unsafe int Y { get; } unsafe C() {} unsafe ~C() {} } "; var src2 = @" using System; delegate void D(); class C { class N { } public event Action<int> A { add { } remove { } } int F() => 0; int X; int Y { get; } C() {} ~C() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe delegate void D();]@17 -> [delegate void D();]@17", "Update [unsafe class N { }]@60 -> [class N { }]@53", "Update [public unsafe event Action<int> A { add { } remove { } }]@84 -> [public event Action<int> A { add { } remove { } }]@70", "Update [unsafe int F() => 0;]@146 -> [int F() => 0;]@125", "Update [unsafe int X;]@172 -> [int X;]@144", "Update [unsafe int Y { get; }]@191 -> [int Y { get; }]@156", "Update [unsafe C() {}]@218 -> [C() {}]@176", "Update [unsafe ~C() {}]@237 -> [~C() {}]@188"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_DeleteInsert() { var srcA1 = "partial class C { unsafe void F() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), }); } [Fact] public void Type_Modifiers_Ref_Add() { var src1 = "public struct C { }"; var src2 = "public ref struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public ref struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public ref struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_Ref_Remove() { var src1 = "public ref struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public ref struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Add() { var src1 = "public struct C { }"; var src2 = "public readonly struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public readonly struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Remove() { var src1 = "public readonly struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public readonly struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime1() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "[A1]class C { }"; var src2 = attribute + "[A2]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]class C { }]@98 -> [[A2]class C { }]@98"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime2() { var src1 = "[System.Obsolete(\"1\")]class C { }"; var src2 = "[System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\")]class C { }]@0 -> [[System.Obsolete(\"2\")]class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A, B]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[B, A]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[B, A]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Change_Reloadable() { var attributeSrc = @" public class A1 : System.Attribute { } public class A2 : System.Attribute { } public class A3 : System.Attribute { } "; var src1 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A1, A2]class C { }"; var src2 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A2, A3]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate, A1, A2]class C { }]@267 -> [[CreateNewOnMetadataUpdate, A2, A3]class C { }]@267"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableRemove() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableAdd() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_ReloadableBase() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@48 -> [[A]class C { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Reorder1() { var src1 = "[A(1), B(2), C(3)]class C { }"; var src2 = "[C(3), A(1), B(2)]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(1), B(2), C(3)]class C { }]@0 -> [[C(3), A(1), B(2)]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_Reorder2() { var src1 = "[A, B, C]class C { }"; var src2 = "[B, C, A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B, C]class C { }]@0 -> [[B, C, A]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_ReorderAndUpdate_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[System.Obsolete(\"1\"), A, B]class C { }"; var src2 = attribute + "[A, B, System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), A, B]class C { }]@96 -> [[A, B, System.Obsolete(\"2\")]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Rename(string keyword) { var src1 = keyword + " C { }"; var src2 = keyword + " D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + keyword + " C { }]@0 -> [" + keyword + " D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, keyword + " D", GetResource(keyword))); } [Fact] public void Type_Rename_AddAndDeleteMember() { var src1 = "class C { int x = 1; }"; var src2 = "class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { int x = 1; }]@0 -> [class D { void F() { } }]@0", "Insert [void F() { }]@10", "Insert [()]@16", "Delete [int x = 1;]@10", "Delete [int x = 1]@10", "Delete [x = 1]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { }]@145 -> [[CreateNewOnMetadataUpdate]class D { }]@145"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable_AddAndDeleteMember() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { int x = 1; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { int x = 1; }]@145 -> [[CreateNewOnMetadataUpdate]class D { void F() { } }]@145", "Insert [void F() { }]@182", "Insert [()]@188", "Delete [int x = 1;]@182", "Delete [int x = 1]@182", "Delete [x = 1]@186"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] public void Interface_NoModifiers_Insert() { var src1 = ""; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { } "; var src2 = "namespace N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoType_Insert() { var src1 = "interface N { }"; var src2 = "interface N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_Insert() { var src1 = ""; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_Insert() { var src1 = ""; var src2 = "struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_BaseType_Add_Unchanged() { var src1 = "class C { }"; var src2 = "class C : object { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : object { }]@0"); edits.VerifySemantics(); } [Fact] public void Type_BaseType_Add_Changed() { var src1 = "class C { }"; var src2 = "class C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("string[]", "string[]?")] [InlineData("object", "dynamic")] [InlineData("dynamic?", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseType_Update_CompileTimeTypeUnchanged() { var src1 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<A> {}"; var src2 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Add() { var src1 = "class C { }"; var src2 = "class C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseInterface_Delete_Inherited() { var src1 = @" interface B {} interface A : B {} class C : A, B {} "; var src2 = @" interface B {} interface A : B {} class C : A {} "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Reorder() { var src1 = "class C : IGoo, IBar { }"; var src2 = "class C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C : IGoo, IBar { }]@0 -> [class C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseInterface_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseInterface_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_Base_Partial() { var srcA1 = "partial class C : B, I { }"; var srcB1 = "partial class C : J { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C : B, I, J { }"; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Base_Partial_InsertDeleteAndUpdate() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "partial class C : D { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "partial class C", FeaturesResources.class_) }), DocumentResults(), }); } [Fact] public void Type_Base_InsertDelete() { var srcA1 = ""; var srcB1 = "class C : B, I { }"; var srcA2 = "class C : B, I { }"; var srcB2 = ""; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Reloadable_NotSupportedByRuntime() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(1); } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void F()", "CreateNewOnMetadataUpdateAttribute")); } [Fact] public void Type_Insert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract class C<T> { public abstract void F(); public virtual void G() {} public override string ToString() => null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Insert_NotSupportedByRuntime() { var src1 = @" public class C { void F() { } }"; var src2 = @" public class C { void F() { } } public class D { void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "public class D", FeaturesResources.class_)); } [Fact] public void Type_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + ""; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"))); } [Fact] public void InterfaceInsert() { var src1 = ""; var src2 = @" public interface I { void F(); static void G() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RefStructInsert() { var src1 = ""; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_ReadOnly_Insert() { var src1 = ""; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_RefModifier_Add() { var src1 = "struct X { }"; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [ref struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "ref struct X", CSharpFeaturesResources.struct_)); } [Fact] public void Struct_ReadonlyModifier_Add() { var src1 = "struct X { }"; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly struct X", SyntaxFacts.GetText(SyntaxKind.StructKeyword))); } [Theory] [InlineData("ref")] [InlineData("readonly")] public void Struct_Modifiers_Partial_InsertDelete(string modifier) { var srcA1 = modifier + " partial struct S { }"; var srcB1 = "partial struct S { }"; var srcA2 = "partial struct S { }"; var srcB2 = modifier + " partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact] public void Class_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; }]@219", "Insert [public override string Get() => string.Empty;]@272", "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@298", "Insert [()]@345"); // Here we add a class implementing an interface and a method inside it with explicit interface specifier. // We want to be sure that adding the method will not tirgger a rude edit as it happens if adding a single method with explicit interface specifier. edits.VerifyRudeDiagnostics(); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void Interface_InsertMembers() { var src1 = @" using System; interface I { } "; var src2 = @" using System; interface I { static int StaticField = 10; static void StaticMethod() { } void VirtualMethod1() { } virtual void VirtualMethod2() { } abstract void AbstractMethod(); sealed void NonVirtualMethod() { } public static int operator +(I a, I b) => 1; static int StaticProperty1 { get => 1; set { } } static int StaticProperty2 => 1; virtual int VirtualProperty1 { get => 1; set { } } virtual int VirtualProperty2 { get => 1; } int VirtualProperty3 { get => 1; set { } } int VirtualProperty4 { get => 1; } abstract int AbstractProperty1 { get; set; } abstract int AbstractProperty2 { get; } sealed int NonVirtualProperty => 1; int this[byte virtualIndexer] => 1; int this[sbyte virtualIndexer] { get => 1; } virtual int this[ushort virtualIndexer] { get => 1; set {} } virtual int this[short virtualIndexer] { get => 1; set {} } abstract int this[uint abstractIndexer] { get; set; } abstract int this[int abstractIndexer] { get; } sealed int this[ulong nonVirtualIndexer] { get => 1; set {} } sealed int this[long nonVirtualIndexer] { get => 1; set {} } static event Action StaticEvent; static event Action StaticEvent2 { add { } remove { } } event Action VirtualEvent { add { } remove { } } abstract event Action AbstractEvent; sealed event Action NonVirtualEvent { add { } remove { } } abstract class C { } interface J { } enum E { } delegate void D(); } "; var edits = GetTopEdits(src1, src2); // TODO: InsertIntoInterface errors are reported due to https://github.com/dotnet/roslyn/issues/37128. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoInterface, "static void StaticMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "void VirtualMethod1()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "virtual void VirtualMethod2()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "abstract void AbstractMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed void NonVirtualMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertOperator, "public static int operator +(I a, I b)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty3", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty4", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[sbyte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[ushort virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[short virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[uint abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[int abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[ulong nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[long nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "static event Action StaticEvent2", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertVirtual, "event Action VirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed event Action NonVirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticField = 10", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticEvent", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertVirtual, "AbstractEvent", CSharpFeaturesResources.event_field)); } [Fact] public void Interface_InsertDelete() { var srcA1 = @" interface I { static void M() { } } "; var srcB1 = @" "; var srcA2 = @" "; var srcB2 = @" interface I { static void M() { } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("M")) }), }); } [Fact] public void Type_Generic_InsertMembers() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "void M()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int this[int i]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoGenericType, "event Action E", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoGenericType, "EF", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F1", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F2", FeaturesResources.field)); } [Fact] public void Type_Generic_InsertMembers_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event System.Action E { add {} remove {} } event System.Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Generic_DeleteInsert() { var srcA1 = @" class C<T> { void F() {} } struct S<T> { void F() {} } interface I<T> { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "struct S<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "interface I<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }) }); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Type_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C<T> { void F() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C<T, S> { int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Delete() { var src1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var src2 = ""; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(CSharpFeaturesResources.struct_, "S")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.interface_, "I"))); } [Fact] public void Type_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var src2 = ReloadableAttributeSrc; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void Type_Partial_DeleteDeclaration() { var srcA1 = "partial class C { void F() {} void M() { } }"; var srcB1 = "partial class C { void G() {} }"; var srcA2 = ""; var srcB2 = "partial class C { void G() {} void M() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.method, "C.F()")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("M")), }) }); } [Fact] public void Type_Partial_InsertFirstDeclaration() { var src1 = ""; var src2 = "partial class C { void F() {} }"; GetTopEdits(src1, src2).VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C"), preserveLocalVariables: false) }); } [Fact] public void Type_Partial_InsertSecondDeclaration() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G"), preserveLocalVariables: false) }), }); } [Fact] public void Type_Partial_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact] public void Type_DeleteInsert() { var srcA1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_DeleteInsert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc; var srcB2 = "[CreateNewOnMetadataUpdate]class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")), }) }); } [Fact] public void Type_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; // TODO: The methods without bodies do not need to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_Attribute_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" abstract class C { [System.Obsolete]public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { [System.Obsolete]void G(); void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_DeleteInsert_DataMembers() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialSplit() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB1 = ""; var srcA2 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB2 = @" partial class C { public int P { get; set; } = 3; } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialMerge() { var srcA1 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB1 = @" partial class C { public int P { get; set; } = 3; }"; var srcA2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB2 = @" "; // note that accessors are not updated since they do not have bodies EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }), DocumentResults() }); } #endregion #region Records [Fact] public void Record_Partial_MovePrimaryConstructor() { var src1 = @" partial record C { } partial record C(int X);"; var src2 = @" partial record C(int X); partial record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Name_Update() { var src1 = "record C { }"; var src2 = "record D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "record D", CSharpFeaturesResources.record_)); } [Fact] public void RecordStruct_NoModifiers_Insert() { var src1 = ""; var src2 = "record struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_AddField() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { private int _y = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "_y = 0", FeaturesResources.field, CSharpFeaturesResources.record_struct)); } [Fact] public void RecordStruct_AddProperty() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { public int Y { get; set; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "public int Y { get; set; } = 0;", FeaturesResources.auto_property, CSharpFeaturesResources.record_struct)); } [Fact] public void Record_NoModifiers_Insert() { var src1 = ""; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_BaseTypeUpdate1() { var src1 = "record C { }"; var src2 = "record C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseTypeUpdate2() { var src1 = "record C : D1 { }"; var src2 = "record C : D2 { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : D1 { }]@0 -> [record C : D2 { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate1() { var src1 = "record C { }"; var src2 = "record C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate2() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate3() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void RecordInsert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract record C<T> { public abstract void F(); public virtual void G() {} public override void H() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_PrintMembers() { var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_ImplementSynthesized_PrintMembers() { var src1 = "record struct C { }"; var src2 = @" record struct C { private readonly bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_WrongParameterName() { // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder sb) { return false; } public virtual bool Equals(C rhs) { return false; } protected C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected virtual bool PrintMembers(System.Text.StringBuilder sb)", "PrintMembers(System.Text.StringBuilder builder)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "public virtual bool Equals(C rhs)", "Equals(C other)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected C(C other)", "C(C original)")); } [Fact] public void Record_ImplementSynthesized_ToString() { var src1 = "record C { }"; var src2 = @" record C { public override string ToString() { return ""R""; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_ToString() { var src1 = @" record C { public override string ToString() { return ""R""; } }"; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_Primary() { var src1 = "record C(int X);"; var src2 = "record C(int X, int Y);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int Y", FeaturesResources.parameter)); } [Fact] public void Record_AddProperty_NotPrimary() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithConstructor() { var src1 = @" record C(int X) { public C(string fromAString) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } public C(string fromAString) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithExplicitMembers() { var src1 = @" record C(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithInitializer() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExplicitMembers() { var src1 = @" record C(int X) { public C(C other) { } }"; var src2 = @" record C(int X) { private int _y; public C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializer() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y = 1; }"; var syntaxMap = GetSyntaxMap(src1, src2); var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializerAndExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_DeleteField() { var src1 = "record C(int X) { private int _y; }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.field, "_y"))); } [Fact] public void Record_DeleteProperty_Primary() { var src1 = "record C(int X, int Y) { }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.parameter, "int Y"))); } [Fact] public void Record_DeleteProperty_NotPrimary() { var src1 = "record C(int X) { public int P { get; set; } }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "P"))); } [Fact] public void Record_ImplementSynthesized_Property() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get { return 4; } init { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithExpressionBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_InitToSet() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterWithSet, "public int X", "X")); } [Fact] public void Record_ImplementSynthesized_Property_MakeReadOnly() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterAsReadOnly, "public int X", "X")); } [Fact] public void Record_UnImplementSynthesized_Property() { var src1 = @" record C(int X) { public int X { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithExpressionBody() { var src1 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithBody() { var src1 = @" record C(int X) { public int X { get { return 4; } init { } } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get; init; } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_ImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_MoveProperty_Partial() { var srcA1 = @" partial record C(int X) { public int Y { get; init; } }"; var srcB1 = @" partial record C; "; var srcA2 = @" partial record C(int X); "; var srcB2 = @" partial record C { public int Y { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").SetMethod) }), }); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializer() { var src1 = @" record C(int X) { public int X { get; init; } = 1; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializerMatchingCompilerGenerated() { var src1 = @" record C(int X) { public int X { get; init; } = X; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Property_Delete_NotPrimary() { var src1 = @" record C(int X) { public int Y { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "Y"))); } [Fact] public void Record_PropertyInitializer_Update_NotPrimary() { var src1 = "record C { int X { get; } = 0; }"; var src2 = "record C { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true)); } [Fact] public void Record_PropertyInitializer_Update_Primary() { var src1 = "record C(int X) { int X { get; } = 0; }"; var src2 = "record C(int X) { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); } #endregion #region Enums [Fact] public void Enum_NoModifiers_Insert() { var src1 = ""; var src2 = "enum C { A }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { }"; var src2 = attribute + "[A]enum E { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum E { }]@48 -> [[A]enum E { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "enum E", FeaturesResources.enum_)); } [Fact] public void Enum_Member_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A]X }"; var src2 = attribute + "enum E { X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]X]@57 -> [X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { X }"; var src2 = attribute + "enum E { [A]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [X]@57 -> [[A]X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Update() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A1]X }"; var src2 = attribute + "enum E { [A2]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]X]@107 -> [[A2]X]@107"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A2]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_InsertDeleteAndUpdate() { var srcA1 = ""; var srcB1 = "enum N { A = 1 }"; var srcA2 = "enum N { [System.Obsolete]A = 1 }"; var srcB2 = ""; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.A")) }), DocumentResults() }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Enum_Rename() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Colors { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Colors { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "enum Colors", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : ushort { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : ushort { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add_Unchanged() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : int { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : int { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Update() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color : long { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color : long { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Delete_Unchanged() { var src1 = "enum Color : int { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : int { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Delete_Changed() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityChange() { var src1 = "public enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityNoChange() { var src1 = "internal enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void EnumInitializerUpdate() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 3, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Blue = 2]@22 -> [Blue = 3]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 3", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate2() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1 << 0, Blue = 2 << 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@13 -> [Red = 1 << 0]@13", "Update [Blue = 2]@22 -> [Blue = 2 << 1]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 2 << 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate3() { var src1 = "enum Color { Red = int.MinValue }"; var src2 = "enum Color { Red = int.MaxValue }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = int.MinValue]@13 -> [Red = int.MaxValue]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = int.MaxValue", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 1 }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 2 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@185 -> [Red = 2]@185"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("Color"))); } [Fact] public void EnumInitializerAdd() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Red = 1]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerDelete() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red = 1]@13 -> [Red]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, Blue}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberAdd2() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd3() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue,}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red, Blue,}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberUpdate() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Orange }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Orange]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "Orange", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberDelete() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red, Blue}]@0 -> [enum Color { Red }]@0", "Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [Fact] public void EnumMemberDelete2() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd_WithInitializer() { var src1 = "enum Color { Red = 1 }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1 }]@0 -> [enum Color { Red = 1, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete_WithInitializer() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red = 1 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, }]@0 -> [enum Color { Red = 1 }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } #endregion #region Delegates [Fact] public void Delegates_NoModifiers_Insert() { var src1 = ""; var src2 = "delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Public_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { public delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate void D();]@10", "Insert [()]@32"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Generic_Insert() { var src1 = "class C { }"; var src2 = "class C { private delegate void D<T>(T a); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private delegate void D<T>(T a);]@10", "Insert [<T>]@33", "Insert [(T a)]@36", "Insert [T]@34", "Insert [T a]@37"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Delete() { var src1 = "class C { private delegate void D(); }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [private delegate void D();]@10", "Delete [()]@33"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.delegate_, "D"))); } [Fact] public void Delegates_Rename() { var src1 = "public delegate void D();"; var src2 = "public delegate void Z();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [public delegate void Z();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "public delegate void Z()", FeaturesResources.delegate_)); } [Fact] public void Delegates_Accessibility_Update() { var src1 = "public delegate void D();"; var src2 = "private delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [private delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@39 -> [[return: A]public delegate int D(int a);]@39"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_Parameter_Delete() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.parameter, "int a"))); } [Fact] public void Delegates_Parameter_Rename() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "int b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Update() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(byte a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [byte a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "byte a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@70 -> [[A]int a]@70"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@61 -> [[A]int a]@61"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_TypeParameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<T>]@21", "Insert [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "T", FeaturesResources.type_parameter)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Delegates_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D<out T>();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D<in T, out S>(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_TypeParameter_Delete() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<T>]@21", "Delete [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void Delegates_TypeParameter_Rename() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<S>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [S]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void Delegates_TypeParameter_Variance1() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance2() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance3() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_AddAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D<T>();"; var src2 = attribute + "public delegate int D<[A]T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@70 -> [[A]T]@70"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_Attribute_Add_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public delegate int D(int a)", FeaturesResources.delegate_)); } [Fact] public void Delegates_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Attribute_Add_WithReturnTypeAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A][A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[return: A][A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertWhole() { var src1 = ""; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate int D(in int b);]@0", "Insert [(in int b)]@21", "Insert [in int b]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_Parameter_Update() { var src1 = "public delegate int D(int b);"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@22 -> [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Insert() { var src1 = ""; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate ref readonly int D();]@0", "Insert [()]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate ref readonly int D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate ref readonly int D()", FeaturesResources.delegate_)); } #endregion #region Nested Types [Fact] public void NestedClass_ClassMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { } class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class D { }]@10 -> @12"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassMove2() { var src1 = @"class C { class D { } class E { } class F { } }"; var src2 = @"class C { class D { } class F { } } class E { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class E { }]@23 -> @37"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class E", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassInsertMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { class E { class D { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class E { class D { } }]@10", "Move [class D { }]@10 -> @20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_Insert1() { var src1 = @"class C { }"; var src2 = @"class C { class D { class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class D { class E { } }]@10", "Insert [class E { }]@20"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert2() { var src1 = @"class C { }"; var src2 = @"class C { protected class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [protected class D { public class E { } }]@10", "Insert [public class E { }]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert3() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public class E { } }]@10", "Insert [public class E { }]@28"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert4() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public D(int a, int b) { } public int P { get; set; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public D(int a, int b) { } public int P { get; set; } }]@10", "Insert [public D(int a, int b) { }]@28", "Insert [public int P { get; set; }]@55", "Insert [(int a, int b)]@36", "Insert [{ get; set; }]@68", "Insert [int a]@37", "Insert [int b]@44", "Insert [get;]@70", "Insert [set;]@75"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable1() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable2() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable3() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable4() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_Insert_Member_Reloadable() { var src1 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { } }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { int x; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_InsertMemberWithInitializer1() { var src1 = @" class C { }"; var src2 = @" class C { private class D { public int P = 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"), preserveLocalVariables: false) }); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public extern D(); public static extern int P { [DllImport(""msvcrt.dll"")]get; [DllImport(""msvcrt.dll"")]set; } [DllImport(""msvcrt.dll"")] public static extern int puts(string c); [DllImport(""msvcrt.dll"")] public static extern int operator +(D d, D g); [DllImport(""msvcrt.dll"")] public static extern explicit operator int (D d); } } "; var edits = GetTopEdits(src1, src2); // Adding P/Invoke is not supported by the CLR. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "public extern D()", FeaturesResources.constructor), Diagnostic(RudeEditKind.InsertExtern, "public static extern int P", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "public static extern int puts(string c)", FeaturesResources.method), Diagnostic(RudeEditKind.InsertExtern, "public static extern int operator +(D d, D g)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertExtern, "public static extern explicit operator int (D d)", CSharpFeaturesResources.conversion_operator)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_VirtualAbstract() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public abstract int P { get; } public abstract int this[int i] { get; } public abstract int puts(string c); public virtual event Action E { add { } remove { } } public virtual int Q { get { return 1; } } public virtual int this[string i] { get { return 1; } } public virtual int M(string c) { return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_TypeReorder1() { var src1 = @"class C { struct E { } class F { } delegate void D(); interface I {} }"; var src2 = @"class C { class F { } interface I {} delegate void D(); struct E { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [struct E { }]@10 -> @56", "Reorder [interface I {}]@54 -> @22"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_MethodDeleteInsert() { var src1 = @"public class C { public void goo() {} }"; var src2 = @"public class C { private class D { public void goo() {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public void goo() {} }]@17", "Insert [public void goo() {}]@35", "Insert [()]@50", "Delete [public void goo() {}]@17", "Delete [()]@32"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "public class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void NestedClass_ClassDeleteInsert() { var src1 = @"public class C { public class X {} }"; var src2 = @"public class C { public class D { public class X {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public class D { public class X {} }]@17", "Move [public class X {}]@17 -> @34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "public class X", FeaturesResources.class_)); } /// <summary> /// A new generic type can be added whether it's nested and inherits generic parameters from the containing type, or top-level. /// </summary> [Fact] public void NestedClassGeneric_Insert() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { class D {} struct S {} enum N {} interface I {} delegate void D(); } class D<T> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedEnum_InsertMember() { var src1 = "struct S { enum N { A = 1 } }"; var src2 = "struct S { enum N { A = 1, B = 2 } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum N { A = 1 }]@11 -> [enum N { A = 1, B = 2 }]@11", "Insert [B = 2]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value)); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "A = 2", FeaturesResources.enum_value), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateBase() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N : uint { A = 1 } }"; var srcA2 = "partial struct S { enum N : int { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum N", FeaturesResources.enum_), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndInsertMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1, B = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( // delegate does not have any user-defined method body and this does not need a PDB update semanticEdits: NoSemanticEdits), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(int x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingParameterTypes, "delegate void D(int x)", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate ref int D(); }"; var srcA2 = "partial struct S { delegate ref readonly int D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.TypeUpdate, "delegate ref readonly int D()", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterValue() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(int x = 1); }"; var srcA2 = "partial struct S { delegate void D(int x = 2); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults() }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndChange() { var srcA1 = "partial struct S { partial class C { void F1() {} } }"; var srcB1 = "partial struct S { partial class C { void F2(byte x) {} } }"; var srcC1 = "partial struct S { }"; var srcA2 = "partial struct S { partial class C { void F1() {} } }"; var srcB2 = "partial struct S { }"; var srcC2 = "partial struct S { partial class C { void F2(int x) {} } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F2(byte x)")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("S").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }) }); } [Fact] public void Type_Partial_AddMultiple() { var srcA1 = ""; var srcB1 = ""; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_Attribute() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "[A]partial class C { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_TypeParameterAttribute_NotSupportedByRuntime() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<[A]T> { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<[A]T>"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteAndChange_Constraint() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<T> where T : new() { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<T>"), Diagnostic(RudeEditKind.ChangingConstraints, "where T : new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : new()") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteRefactor() { var srcA1 = "partial class C : I { void F() { } }"; var srcB1 = "[A][B]partial class C : J { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C : I, J { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; var srcE = "interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE, srcE) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G")) }), DocumentResults(), }); } [Fact] public void Type_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C { }" + attributes; var srcB1 = "partial class C { }"; var srcA2 = "[A]partial class C { }" + attributes; var srcB2 = "[B]partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting() { var srcA1 = "partial class C { void F() { } }"; var srcB1 = "[A,B]partial class C { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")) }), }); } [Fact] public void Type_Partial_InsertDeleteChangeMember() { var srcA1 = "partial class C { void F(int y = 1) { } }"; var srcB1 = "partial class C { void G(int x = 1) { } }"; var srcC1 = ""; var srcA2 = ""; var srcB2 = "partial class C { void G(int x = 2) { } }"; var srcC2 = "partial class C { void F(int y = 2) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int y = 2", FeaturesResources.parameter) }), }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndInsertVirtual() { var srcA1 = "partial interface I { partial class C { virtual void F1() {} } }"; var srcB1 = "partial interface I { partial class C { virtual void F2() {} } }"; var srcC1 = "partial interface I { partial class C { } }"; var srcD1 = "partial interface I { partial class C { } }"; var srcE1 = "partial interface I { }"; var srcF1 = "partial interface I { }"; var srcA2 = "partial interface I { partial class C { } }"; var srcB2 = ""; var srcC2 = "partial interface I { partial class C { virtual void F1() {} } }"; // move existing virtual into existing partial decl var srcD2 = "partial interface I { partial class C { virtual void N1() {} } }"; // insert new virtual into existing partial decl var srcE2 = "partial interface I { partial class C { virtual void F2() {} } }"; // move existing virtual into a new partial decl var srcF2 = "partial interface I { partial class C { virtual void N2() {} } }"; // insert new virtual into new partial decl EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE1, srcE2), GetTopEdits(srcF1, srcF2) }, new[] { // A DocumentResults(), // B DocumentResults(), // C DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F1")) }), // D DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N1()", FeaturesResources.method) }), // E DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }), // F DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N2()", FeaturesResources.method) }), }); } #endregion #region Namespaces [Fact] public void Namespace_Insert() { var src1 = @""; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_InsertNested() { var src1 = @"namespace C { }"; var src2 = @"namespace C { namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_DeleteNested() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_Move() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { } namespace D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [namespace D { }]@14 -> @16"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_Reorder1() { var src1 = @"namespace C { namespace D { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@30 -> @30", "Reorder [namespace E { }]@42 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_Reorder2() { var src1 = @"namespace C { namespace D1 { } namespace D2 { } namespace D3 { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D1 { } namespace D2 { } namespace D3 { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@65 -> @65", "Reorder [namespace E { }]@77 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_FileScoped_Insert() { var src1 = @""; var src2 = @"namespace C;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_FileScoped_Delete() { var src1 = @"namespace C;"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_)); } #endregion #region Members [Fact] public void PartialMember_DeleteInsert_SingleDocument() { var src1 = @" using System; partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1; int F2; } partial class C { } "; var src2 = @" using System; partial class C { } partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void M() {}]@68", "Insert [int P1 { get; set; }]@85", "Insert [int P2 { get => 1; set {} }]@111", "Insert [int this[int i] { get => 1; set {} }]@144", "Insert [int this[byte i] { get => 1; set {} }]@186", "Insert [event Action E { add {} remove {} }]@229", "Insert [event Action EF;]@270", "Insert [int F1, F2;]@292", "Insert [()]@74", "Insert [{ get; set; }]@92", "Insert [{ get => 1; set {} }]@118", "Insert [[int i]]@152", "Insert [{ get => 1; set {} }]@160", "Insert [[byte i]]@194", "Insert [{ get => 1; set {} }]@203", "Insert [{ add {} remove {} }]@244", "Insert [Action EF]@276", "Insert [int F1, F2]@292", "Insert [get;]@94", "Insert [set;]@99", "Insert [get => 1;]@120", "Insert [set {}]@130", "Insert [int i]@153", "Insert [get => 1;]@162", "Insert [set {}]@172", "Insert [byte i]@195", "Insert [get => 1;]@205", "Insert [set {}]@215", "Insert [add {}]@246", "Insert [remove {}]@253", "Insert [EF]@283", "Insert [F1]@296", "Insert [F2]@300", "Delete [void M() {}]@43", "Delete [()]@49", "Delete [int P1 { get; set; }]@60", "Delete [{ get; set; }]@67", "Delete [get;]@69", "Delete [set;]@74", "Delete [int P2 { get => 1; set {} }]@86", "Delete [{ get => 1; set {} }]@93", "Delete [get => 1;]@95", "Delete [set {}]@105", "Delete [int this[int i] { get => 1; set {} }]@119", "Delete [[int i]]@127", "Delete [int i]@128", "Delete [{ get => 1; set {} }]@135", "Delete [get => 1;]@137", "Delete [set {}]@147", "Delete [int this[byte i] { get => 1; set {} }]@161", "Delete [[byte i]]@169", "Delete [byte i]@170", "Delete [{ get => 1; set {} }]@178", "Delete [get => 1;]@180", "Delete [set {}]@190", "Delete [event Action E { add {} remove {} }]@204", "Delete [{ add {} remove {} }]@219", "Delete [add {}]@221", "Delete [remove {}]@228", "Delete [event Action EF;]@245", "Delete [Action EF]@251", "Delete [EF]@258", "Delete [int F1;]@267", "Delete [int F1]@267", "Delete [F1]@271", "Delete [int F2;]@280", "Delete [int F2]@280", "Delete [F2]@284"); EditAndContinueValidation.VerifySemantics( new[] { edits }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod, preserveLocalVariables: false), }) }); } [Fact] public void PartialMember_InsertDelete_MultipleDocuments() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() {} }"; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"), preserveLocalVariables: false) }), DocumentResults() }); } [Fact] public void PartialMember_DeleteInsert_MultipleDocuments() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"), preserveLocalVariables: false) }) }); } [Fact] public void PartialMember_DeleteInsert_GenericMethod() { var srcA1 = "partial class C { void F<T>() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F<T>() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<T>()"), Diagnostic(RudeEditKind.GenericMethodUpdate, "T") }) }); } [Fact] public void PartialMember_DeleteInsert_GenericType() { var srcA1 = "partial class C<T> { void F() {} }"; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<T> { }"; var srcB2 = "partial class C<T> { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()") }) }); } [Fact] public void PartialMember_DeleteInsert_Destructor() { var srcA1 = "partial class C { ~C() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { ~C() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("Finalize"), preserveLocalVariables: false), }) }); } [Fact] public void PartialNestedType_InsertDeleteAndChange() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { class D { void M() {} } interface I { } }"; var srcA2 = "partial class C { class D : I { void M() {} } interface I { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class D", FeaturesResources.class_), }), DocumentResults() }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void PartialMember_RenameInsertDelete() { // The syntactic analysis for A and B produce rename edits since it doesn't see that the member was in fact moved. // TODO: Currently, we don't even pass rename edits to semantic analysis where we could handle them as updates. var srcA1 = "partial class C { void F1() {} }"; var srcB1 = "partial class C { void F2() {} }"; var srcA2 = "partial class C { void F2() {} }"; var srcB2 = "partial class C { void F1() {} }"; // current outcome: GetTopEdits(srcA1, srcA2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F2()", FeaturesResources.method)); GetTopEdits(srcB1, srcB2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F1()", FeaturesResources.method)); // correct outcome: //EditAndContinueValidation.VerifySemantics( // new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, // new[] // { // DocumentResults(semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), // }), // DocumentResults( // semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F1")), // }) // }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodBodyError() { var srcA1 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; } } "; var srcB1 = @" using System.Collections.Generic; partial class C { } "; var srcA2 = @" using System.Collections.Generic; partial class C { } "; var srcB2 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; yield return 2; } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdatePropertyAccessors() { var srcA1 = "partial class C { int P { get => 1; set { Console.WriteLine(1); } } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateAutoProperty() { var srcA1 = "partial class C { int P => 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P => 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_AddFieldInitializer() { var srcA1 = "partial class C { int f; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f = 1; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_RemoveFieldInitializer() { var srcA1 = "partial class C { int f = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_ConstructorWithInitializers() { var srcA1 = "partial class C { int f = 1; C(int x) { f = x; } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { int f = 1; }"; var srcB2 = "partial class C { C(int x) { f = x + 1; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F() {} }"; var srcA2 = "partial struct S { void F(int x) {} }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodParameterType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(int x); }"; var srcA2 = "partial struct S { void F(byte x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F(int x)")) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddTypeParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(); }"; var srcA2 = "partial struct S { void F<T>(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertGenericMethod, "void F<T>()", FeaturesResources.method) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Methods [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Method_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F() => 0; }"; var src2 = "class C { " + newModifiers + "int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F() => 0;]@10 -> [" + newModifiers + "int F() => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F()", FeaturesResources.method)); } [Fact] public void Method_NewModifier_Add() { var src1 = "class C { int F() => 0; }"; var src2 = "class C { new int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int F() => 0;]@10 -> [new int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_NewModifier_Remove() { var src1 = "class C { new int F() => 0; }"; var src2 = "class C { int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [new int F() => 0;]@10 -> [int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_ReadOnlyModifier_Add_InMutableStruct() { var src1 = @" struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct1() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" readonly struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough the body nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IMethodSymbol>("M"))); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct2() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "struct S", "struct")); } [Fact] public void Method_AsyncModifier_Remove() { var src1 = @" class Test { public async Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public Task<int> WaitAsync() { return Task.FromResult(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "public Task<int> WaitAsync()", FeaturesResources.method)); } [Fact] public void Method_AsyncModifier_Add() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void Method_AsyncModifier_Add_NotSupported() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodAsync, "public async Task<int> WaitAsync()")); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Method_ReturnType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Method_ReturnType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " M()", FeaturesResources.method)); } [Fact] public void Method_Update() { var src1 = @" class C { static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); } } "; var src2 = @" class C { static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); }]@18 -> [static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); }]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact] public void MethodWithExpressionBody_Update() { var src1 = @" class C { static int Main(string[] args) => F(1); static int F(int a) => 1; } "; var src2 = @" class C { static int Main(string[] args) => F(2); static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static int Main(string[] args) => F(1);]@18 -> [static int Main(string[] args) => F(2);]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void MethodWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int M(int a) => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int M(int a) => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M(int a) => new Func<int>(() => a + 1)();]@35 -> [int M(int a) => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact] public void MethodWithExpressionBody_ToBlockBody() { var src1 = "class C { static int F(int a) => 1; }"; var src2 = "class C { static int F(int a) { return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => 1;]@10 -> [static int F(int a) { return 2; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithBlockBody_ToExpressionBody() { var src1 = "class C { static int F(int a) { return 2; } }"; var src2 = "class C { static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) { return 2; }]@10 -> [static int F(int a) => 1;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithLambda_Update() { var src1 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; } } "; var src2 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap[0]) }); } [Fact] public void MethodUpdate_LocalVariableDeclaration() { var src1 = @" class C { static void Main(string[] args) { int x = 1; Console.WriteLine(x); } } "; var src2 = @" class C { static void Main(string[] args) { int x = 2; Console.WriteLine(x); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int x = 1; Console.WriteLine(x); }]@18 -> [static void Main(string[] args) { int x = 2; Console.WriteLine(x); }]@18"); } [Fact] public void Method_Delete() { var src1 = @" class C { void goo() { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [void goo() { }]@18", "Delete [()]@26"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void MethodWithExpressionBody_Delete() { var src1 = @" class C { int goo() => 1; } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int goo() => 1;]@18", "Delete [()]@25"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_WithParameterAndAttribute() { var src1 = @" class C { [Obsolete] void goo(int a) { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[Obsolete] void goo(int a) { }]@18", "Delete [(int a)]@42", "Delete [int a]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo(int a)"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int puts(string c); } "; var src2 = @" using System; using System.Runtime.InteropServices; class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[DllImport(""msvcrt.dll"")] public static extern int puts(string c);]@74", "Delete [(string c)]@134", "Delete [string c]@135"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "puts(string c)"))); } [Fact] public void MethodInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { void goo() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "void goo()", FeaturesResources.method)); } [Fact] public void PrivateMethodInsert() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { void goo() { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo() { }]@18", "Insert [()]@26"); edits.VerifyRudeDiagnostics(); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithParameters() { var src1 = @" using System; class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" using System; class C { void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo(int a) { }]@35", "Insert [(int a)]@43", "Insert [int a]@44"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.goo")) }); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithAttribute() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { [System.Obsolete] void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[System.Obsolete] void goo(int a) { }]@18", "Insert [(int a)]@49", "Insert [int a]@50"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodInsert_Virtual() { var src1 = @" class C { }"; var src2 = @" class C { public virtual void F() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public virtual void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Abstract() { var src1 = @" abstract class C { }"; var src2 = @" abstract class C { public abstract void F(); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public abstract void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Override() { var src1 = @" class C { }"; var src2 = @" class C { public override void F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public override void F()", FeaturesResources.method)); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void ExternMethodInsert() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[DllImport(""msvcrt.dll"")] private static extern int puts(string c);]@74", "Insert [(string c)]@135", "Insert [string c]@136"); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int puts(string c)", FeaturesResources.method)); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethodDeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; // TODO: The method does not need to be updated since there are no sequence points generated for it. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethod_Attribute_DeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] [Obsolete] private static extern int puts(string c); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodReorder1() { var src1 = "class C { void f(int a, int b) { a = b; } void g() { } }"; var src2 = "class C { void g() { } void f(int a, int b) { a = b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Reorder [void g() { }]@42 -> @10"); } [Fact] public void MethodInsertDelete1() { var src1 = "class C { class D { } void f(int a, int b) { a = b; } }"; var src2 = "class C { class D { void f(int a, int b) { a = b; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void f(int a, int b) { a = b; }]@20", "Insert [(int a, int b)]@26", "Insert [int a]@27", "Insert [int b]@34", "Delete [void f(int a, int b) { a = b; }]@22", "Delete [(int a, int b)]@28", "Delete [int a]@29", "Delete [int b]@36"); } [Fact] public void MethodUpdate_AddParameter() { var src1 = @" class C { static void Main() { } }"; var src2 = @" class C { static void Main(string[] args) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string[] args]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "string[] args", FeaturesResources.parameter)); } [Fact] public void MethodUpdate_UpdateParameter() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [string[] args]@35 -> [string[] b]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_UpdateParameterAndBody() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { System.Console.Write(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Method_Name_Update() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void EntryPoint(string[] args) { } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [static void Main(string[] args) { }]@18 -> [static void EntryPoint(string[] args) { }]@18"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "static void EntryPoint(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AsyncMethod0() { var src1 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(500); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AsyncMethod1() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; }]@151 -> [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; }]@151"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddReturnTypeAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [return: Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[return: Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute_SupportedByRuntime() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Test.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 4, 5, 6})] void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter_NoChange() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 1; } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddAttribute2() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute3() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute4() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete("""")] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodUpdate_DeleteAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute2() { var src1 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute3() { var src1 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_ExplicitlyImplemented1() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(2); } void J.Goo() { Console.WriteLine(1); } }"; var src2 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(2); }]@25 -> [void I.Goo() { Console.WriteLine(1); }]@25", "Update [void J.Goo() { Console.WriteLine(1); }]@69 -> [void J.Goo() { Console.WriteLine(2); }]@69"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_ExplicitlyImplemented2() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var src2 = @" class C : I, J { void Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(1); }]@25 -> [void Goo() { Console.WriteLine(1); }]@25"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "void Goo()", FeaturesResources.method)); } [WorkItem(754255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754255")] [Fact] public void MethodUpdate_UpdateStackAlloc() { var src1 = @" class C { static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } } }"; var src2 = @" class C { static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } } }"; var expectedEdit = @"Update [static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } }]@18 -> [static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } }]@18"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Theory] [InlineData("stackalloc int[3]")] [InlineData("stackalloc int[3] { 1, 2, 3 }")] [InlineData("stackalloc int[] { 1, 2, 3 }")] [InlineData("stackalloc[] { 1, 2, 3 }")] public void MethodUpdate_UpdateStackAlloc2(string stackallocDecl) { var src1 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 1; } }"; var src2 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda1() { var src1 = "unsafe class C { void M() { F(1, () => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, () => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda2() { var src1 = "unsafe class C { void M() { F(1, x => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, x => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInAnonymousMethod() { var src1 = "unsafe class C { void M() { F(1, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLocalFunction() { var src1 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(1); } }"; var src2 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda1() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda2() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLocalFunction() { var src1 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(1); } }"; var src2 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInQuery() { var src1 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 1; } }"; var src2 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_UpdateAnonymousMethod() { var src1 = "class C { void M() => F(1, delegate(int a) { return a; }); }"; var src2 = "class C { void M() => F(2, delegate(int a) { return a; }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Query() { var src1 = "class C { void M() { F(1, from goo in bar select baz); } }"; var src2 = "class C { void M() { F(2, from goo in bar select baz); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_Query() { var src1 = "class C { void M() => F(1, from goo in bar select baz); }"; var src2 = "class C { void M() => F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AnonymousType() { var src1 = "class C { void M() { F(1, new { A = 1, B = 2 }); } }"; var src2 = "class C { void M() { F(2, new { A = 1, B = 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_AnonymousType() { var src1 = "class C { void M() => F(new { A = 1, B = 2 }); }"; var src2 = "class C { void M() => F(new { A = 10, B = 20 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Iterator_YieldReturn() { var src1 = "class C { IEnumerable<int> M() { yield return 1; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AddYieldReturn() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void MethodUpdate_AddYieldReturn_NotSupported() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodIterator, "IEnumerable<int> M()")); } [Fact] public void MethodUpdate_Iterator_YieldBreak() { var src1 = "class C { IEnumerable<int> M() { F(); yield break; } }"; var src2 = "class C { IEnumerable<int> M() { G(); yield break; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [WorkItem(1087305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087305")] [Fact] public void MethodUpdate_LabeledStatement() { var src1 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(1); } } }"; var src2 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_LocalFunctionsParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { void f(ref int b) => b = 1; } }"; var src2 = @"class C { public void M(int a) { void f(out int b) => b = 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { void f(ref int b) => b = 1; }]@10 -> [public void M(int a) { void f(out int b) => b = 1; }]@10"); } [Fact] public void MethodUpdate_LambdaParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { f((ref int b) => b = 1); } }"; var src2 = @"class C { public void M(int a) { f((out int b) => b = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { f((ref int b) => b = 1); }]@10 -> [public void M(int a) { f((out int b) => b = 1); }]@10"); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int M(in int b) => throw null;]@13", "Insert [(in int b)]@18", "Insert [in int b]@19"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int M(int b) => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@19 -> [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int M() => throw null;]@13", "Insert [()]@31"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M() => throw null;]@13 -> [ref readonly int M() => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@345"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, "string IConflict.Get()", FeaturesResources.method)); } [Fact] public void Method_Partial_DeleteInsert_DefinitionPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { partial void F() { } }"; var srcC2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteInsert_ImplementationPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void Method_Partial_Swap_ImplementationAndDefinitionParts() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F() { } }"; var srcB2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteImplementation() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteInsertBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcD1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F(); }"; var srcD2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }) }); } [Fact] public void Method_Partial_Insert() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact] public void Method_Partial_Insert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } #endregion #region Operators [Theory] [InlineData("implicit", "explicit")] [InlineData("explicit", "implicit")] public void Operator_Modifiers_Update(string oldModifiers, string newModifiers) { var src1 = "class C { public static " + oldModifiers + " operator int (C c) => 0; }"; var src2 = "class C { public static " + newModifiers + " operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static " + oldModifiers + " operator int (C c) => 0;]@10 -> [public static " + newModifiers + " operator int (C c) => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static " + newModifiers + " operator int (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Modifiers_Update_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static implicit operator int (C c) => 0; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static explicit operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Operator_Conversion_ExternModifiers_Add() { var src1 = "class C { public static implicit operator bool (C c) => default; }"; var src2 = "class C { extern public static implicit operator bool (C c); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "extern public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Conversion_ExternModifiers_Remove() { var src1 = "class C { extern public static implicit operator bool (C c); }"; var src2 = "class C { public static implicit operator bool (C c) => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void OperatorInsert() { var src1 = @" class C { } "; var src2 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator), Diagnostic(RudeEditKind.InsertOperator, "public static C operator +(C c, C d)", FeaturesResources.operator_)); } [Fact] public void OperatorDelete() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(CSharpFeaturesResources.conversion_operator, "implicit operator bool(C c)")), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.operator_, "operator +(C c, C d)"))); } [Fact] public void OperatorInsertDelete() { var srcA1 = @" partial class C { public static implicit operator bool (C c) => false; } "; var srcB1 = @" partial class C { public static C operator +(C c, C d) => c; } "; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Addition")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Implicit")) }), }); } [Fact] public void OperatorUpdate() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { public static implicit operator bool (C c) { return true; } public static C operator +(C c, C d) { return d; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_Update() { var src1 = @" class C { public static implicit operator bool (C c) => false; public static C operator +(C c, C d) => c; } "; var src2 = @" class C { public static implicit operator bool (C c) => true; public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_ToBlockBody() { var src1 = "class C { public static C operator +(C c, C d) => d; }"; var src2 = "class C { public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) => d;]@10 -> [public static C operator +(C c, C d) { return c; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorWithBlockBody_ToExpressionBody() { var src1 = "class C { public static C operator +(C c, C d) { return c; } }"; var src2 = "class C { public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) { return c; }]@10 -> [public static C operator +(C c, C d) => d;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorReorder1() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static implicit operator int (C c) { return 1; } } "; var src2 = @" class C { public static implicit operator int (C c) { return 1; } public static implicit operator bool (C c) { return false; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static implicit operator int (C c) { return 1; }]@84 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void OperatorReorder2() { var src1 = @" class C { public static C operator +(C c, C d) { return c; } public static C operator -(C c, C d) { return d; } } "; var src2 = @" class C { public static C operator -(C c, C d) { return d; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static C operator -(C c, C d) { return d; }]@74 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Operator_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public static bool operator !(in Test b) => throw null;]@13", "Insert [(in Test b)]@42", "Insert [in Test b]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static bool operator !(in Test b)", FeaturesResources.operator_)); } [Fact] public void Operator_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { public static bool operator !(Test b) => throw null; }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Test b]@43 -> [in Test b]@43"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in Test b", FeaturesResources.parameter)); } #endregion #region Constructor, Destructor [Fact] public void Constructor_Parameter_AddAttribute() { var src1 = @" class C { private int x = 1; public C(int a) { } }"; var src2 = @" class C { private int x = 2; public C([System.Obsolete]int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [x = 1]@30 -> [x = 2]@30", "Update [int a]@53 -> [[System.Obsolete]int a]@53"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] [WorkItem(2068, "https://github.com/dotnet/roslyn/issues/2068")] public void Constructor_ExternModifier_Add() { var src1 = "class C { }"; var src2 = "class C { public extern C(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public extern C();]@10", "Insert [()]@25"); // This can be allowed as the compiler generates an empty constructor, but it's not worth the complexity. edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public extern C()", FeaturesResources.constructor)); } [Fact] public void ConstructorInitializer_Update1() { var src1 = @" class C { public C(int a) : base(a) { } }"; var src2 = @" class C { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@18 -> [public C(int a) : base(a + 1) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update2() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [Fact] public void ConstructorInitializer_Update3() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a) : base(a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) { }]@18 -> [public C(int a) : base(a) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update4() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) : base(a + 1) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [WorkItem(743552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743552")] [Fact] public void ConstructorUpdate_AddParameter() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a, int b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@26 -> [(int a, int b)]@26", "Insert [int b]@34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int b", FeaturesResources.parameter)); } [Fact] public void DestructorDelete() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { }"; var expectedEdit1 = @"Delete [~B() { }]@10"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit1); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] public void DestructorDelete_InsertConstructor() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { B() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [B() { }]@10", "Insert [()]@11", "Delete [~B() { }]@10"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "B()", FeaturesResources.constructor), Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] [WorkItem(789577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789577")] public void ConstructorUpdate_AnonymousTypeInFieldInitializer() { var src1 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 1; } }"; var src2 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_Static_Delete() { var src1 = "class C { static C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.static_constructor, "C()"))); } [Fact] public void Constructor_Static_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { static C() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Constructor_Static_Insert() { var src1 = "class C { }"; var src2 = "class C { static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void InstanceCtorDelete_Public() { var src1 = "class C { public C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("protected internal")] public void InstanceCtorDelete_NonPublic(string accessibility) { var src1 = "class C { [System.Obsolete] " + accessibility + " C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void InstanceCtorDelete_Public_PartialWithInitializerUpdate() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void InstanceCtorInsert_Public_Implicit() { var src1 = "class C { }"; var src2 = "class C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Partial_Public_Implicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // no change in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtorInsert_Public_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }); } [Fact] public void InstanceCtorInsert_Partial_Public_NoImplicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C(int a) { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { public C(int a) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }), // no change in document B DocumentResults(), }); } [Fact] public void InstanceCtorInsert_Private_Implicit1() { var src1 = "class C { }"; var src2 = "class C { private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Private_Implicit2() { var src1 = "class C { }"; var src2 = "class C { C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Protected_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "protected C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorUpdate_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Private_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C") .InstanceConstructors.Single(ctor => ctor.DeclaredAccessibility == Accessibility.Private)) }); } [Fact] public void InstanceCtorInsert_Internal_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_Protected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_InternalProtected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void StaticCtor_Partial_DeleteInsert() { var srcA1 = "partial class C { static C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { static C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPrivate() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePublicInsertPublic() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPublic() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be reported as rude edit in the other document where it was inserted back with changed accessibility DocumentResults( semanticEdits: NoSemanticEdits), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), }); } [Fact] public void StaticCtor_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { static C() { } }"; var srcA2 = "partial class C { static C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePublic() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPrivateDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { private C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_DeleteInternalInsertInternal() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeleteInternal_WithBody() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { Console.WriteLine(1); } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), // delete of the constructor in partial part will be reported as rude in the the other document where it was inserted with changed accessibility DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor) }), DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 2</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_Trivia1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); /*new trivia*/public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_ExplicitInterfaceImpl1() { var src1 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 1</N:0.3>); } } "; var src2 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 2</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_Parameterless_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO: //var syntaxMap = GetSyntaxMap(src1, src2); //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_WithParameters_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO: bug https://github.com/dotnet/roslyn/issues/2504 //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a <N:0.0>= 1</N:0.0>; C(uint arg) => Console.WriteLine(2); } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a <N:0.0>= 2</N:0.0>; // updated field initializer C(uint arg) => Console.WriteLine(2); C(byte arg) => Console.WriteLine(3); // new ctor } "; var syntaxMapB = GetSyntaxMap(srcB1, srcB2)[0]; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Int32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Boolean"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "UInt32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Byte"), syntaxMap: null), }) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update_SemanticError() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a = 1; } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a = 2; C(int arg) => Console.WriteLine(2); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), // The actual edits do not matter since there are semantic errors in the compilation. // We just should not crash. DocumentResults(diagnostics: Array.Empty<RudeEditDiagnosticDescription>()) }); } [Fact] public void InstanceCtor_Partial_Implicit_Update() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { int G = 1; }"; var srcA2 = "partial class C { int F = 2; }"; var srcB2 = "partial class C { int G = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void ParameterlessConstructor_SemanticError_Delete1() { var src1 = @" class C { D() {} } "; var src2 = @" class C { } "; var edits = GetTopEdits(src1, src2); // The compiler interprets D() as a constructor declaration. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void Constructor_SemanticError_Partial() { var src1 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(1); } } "; var src2 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("C").PartialImplementationPart) }); } [Fact] public void PartialDeclaration_Delete() { var srcA1 = "partial class C { public C() { } void F() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = ""; var srcB2 = "partial class C { int x = 2; void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert() { var srcA1 = ""; var srcB1 = "partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert_Reloadable() { var srcA1 = ""; var srcB1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_BlockBodyToExpressionBody() { var src1 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var src2 = @" public class C { private int _value; public C(int value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) { _value = value; }]@52 -> [public C(int value) => _value = value;]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_BlockBodyToExpressionBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) : base(value) { _value = value; }]@90 -> [public C(int value) : base(value) => _value = value;]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { private int _value; public C(int value) => _value = value; } "; var src2 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) => _value = value;]@52 -> [public C(int value) { _value = value; }]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_ExpressionBodyToBlockBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) : base(value) => _value = value;]@90 -> [public C(int value) : base(value) { _value = value; }]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_BlockBodyToExpressionBody() { var src1 = @" public class C { ~C() { Console.WriteLine(0); } } "; var src2 = @" public class C { ~C() => Console.WriteLine(0); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() { Console.WriteLine(0); }]@25 -> [~C() => Console.WriteLine(0);]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { ~C() => Console.WriteLine(0); } "; var src2 = @" public class C { ~C() { Console.WriteLine(0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() => Console.WriteLine(0);]@25 -> [~C() { Console.WriteLine(0); }]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [Test(in int b) => throw null;]@13", "Insert [(in int b)]@17", "Insert [in int b]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { Test() => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Constructor_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { Test(int b) => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@18 -> [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } #endregion #region Fields and Properties with Initializers [Fact] public void FieldInitializer_Update1() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update1() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get; } = 1;]@10"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializer_Update2() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializer_Update2() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get { return 1; } }]@10", "Update [get;]@18 -> [get { return 1; }]@18"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)); } [Fact] public void PropertyInitializer_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int a { get; } = 0; }"; var srcA2 = "partial class C { int a { get { return 1; } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults() }); } [Fact] public void FieldInitializer_Update3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update3() { var src1 = "class C { int a { get { return 1; } } }"; var src2 = "class C { int a { get; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get { return 1; } }]@10 -> [int a { get; } = 0;]@10", "Update [get { return 1; }]@18 -> [get;]@18"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21", "Delete [static C() { }]@24", "Delete [()]@32"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2;}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate_Private() { var src1 = "class C { int a; [System.Obsolete]C() { } }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate_Private() { var src1 = "class C { int a { get; } = 1; C() { } }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate_Public() { var src1 = "class C { int a; public C() { } }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate_Public() { var src1 = "class C { int a { get; } = 1; public C() { } }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate2() { var src1 = "class C { int a; public C() { } }"; var src2 = "class C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate2() { var src1 = "class C { int a { get; } = 1; public C() { } }"; var src2 = "class C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate4() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate6() { var src1 = "class C { int a; private C(int a) : this(true) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) : this(true) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertImplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertExplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [static C() { }]@28", "Insert [()]@36", "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorInsertExplicit() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorInsertExplicit() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_GenericType() { var src1 = "class C<T> { int a = 1; }"; var src2 = "class C<T> { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@17 -> [a = 2]@17"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "a = 2"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void PropertyInitializerUpdate_GenericType() { var src1 = "class C<T> { int a { get; } = 1; }"; var src2 = "class C<T> { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "int a"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void FieldInitializerUpdate_StackAllocInConstructor() { var src1 = "unsafe class C { int a = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@21 -> [a = 2]@21"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void FieldInitializerUpdate_SwitchExpressionInConstructor() { var src1 = "class C { int a = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor1() { var src1 = "unsafe class C { int a { get; } = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor2() { var src1 = "unsafe class C { int a { get; } = 1; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor3() { var src1 = "unsafe class C { int a { get; } = 1; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor1() { var src1 = "class C { int a { get; } = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor2() { var src1 = "class C { int a { get; } = 1; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var src2 = "class C { int a { get; } = 2; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor3() { var src1 = "class C { int a { get; } = 1; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@14 -> [a = 2]@14"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a { get; } = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a { get; } = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@33 -> [a = 2]@33"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a { get; } = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a { get; } = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a { get; } = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a { get; } = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a = 1; }"; var src2 = "partial class C { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a { get; } = 1; }"; var src2 = "partial class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a = 1; } partial class C { }"; var src2 = "partial class C { int a = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a { get; } = 1; } partial class C { }"; var src2 = "partial class C { int a { get; } = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a = F(1, (x, y) => x + y); }"; var src2 = "class C { int a = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a { get; } = F(1, (x, y) => x + y); }"; var src2 = "class C { int a { get; } = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_SimpleLambda() { var src1 = "class C { int a = F(1, x => x); }"; var src2 = "class C { int a = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_SimpleLambda() { var src1 = "class C { int a { get; } = F(1, x => x); }"; var src2 = "class C { int a { get; } = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Query() { var src1 = "class C { int a = F(1, from goo in bar select baz); }"; var src2 = "class C { int a = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_Query() { var src1 = "class C { int a { get; } = F(1, from goo in bar select baz); }"; var src2 = "class C { int a { get; } = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousType() { var src1 = "class C { int a = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousType() { var src1 = "class C { int a { get; } = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a { get; } = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) {} public C(bool b) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) {} public C(bool b) {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 2</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_EditConstructorNotIncludingInitializers() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_RemoveCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_AddCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_UpdateBaseCtorInitializerWithLambdas1() { var src1 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 1</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 2</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_PartialDeclarationDelete_SingleDocument() { var src1 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); } partial class C { public C() { } static int F(Func<int, int> x) => 1; } "; var src2 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); static int F(Func<int, int> x) => 1; } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), syntaxMap[0]), }); } [Fact] public void FieldInitializerUpdate_ActiveStatements1() { var src1 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 1; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 2; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); var activeStatements = GetActiveStatements(src1, src2); edits.VerifySemantics( activeStatements, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]), }); } [Fact] public void PropertyWithInitializer_SemanticError_Partial() { var src1 = @" partial class C { partial int P => 1; } partial class C { partial int P => 1; } "; var src2 = @" partial class C { partial int P => 1; } partial class C { partial int P => 2; public C() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => ((IPropertySymbol)c.GetMember<INamedTypeSymbol>("C").GetMembers("P").First()).GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Partial_DeleteInsert_InitializerRemoval() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void Field_Partial_DeleteInsert_InitializerUpdate() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } #endregion #region Fields [Fact] public void Field_Rename() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int b = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [b = 0]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "b = 0", FeaturesResources.field)); } [Fact] public void Field_Kind_Update() { var src1 = "class C { Action a; }"; var src2 = "class C { event Action a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Action a;]@10 -> [event Action a;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FieldKindUpdate, "event Action a", FeaturesResources.event_)); } [Theory] [InlineData("static")] [InlineData("volatile")] [InlineData("const")] public void Field_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F = 0; }"; var src2 = "class C { " + newModifiers + "int F = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F = 0;]@10 -> [" + newModifiers + "int F = 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F = 0", FeaturesResources.field)); } [Fact] public void Field_Modifier_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { static int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ModifiersUpdate, "F", FeaturesResources.field) }), DocumentResults(), }); } [Fact] public void Field_Attribute_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { [System.Obsolete]int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_FixedSize_Update() { var src1 = "struct S { public unsafe fixed byte a[1], b[2]; }"; var src2 = "struct S { public unsafe fixed byte a[2], b[3]; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a[1]]@36 -> [a[2]]@36", "Update [b[2]]@42 -> [b[3]]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "a[2]", FeaturesResources.field), Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "b[3]", FeaturesResources.field)); } [WorkItem(1120407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120407")] [Fact] public void Field_Const_Update() { var src1 = "class C { const int x = 0; }"; var src2 = "class C { const int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [x = 0]@20 -> [x = 1]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "x = 1", FeaturesResources.const_field)); } [Fact] public void Field_Event_VariableDeclarator_Update() { var src1 = "class C { event Action a; }"; var src2 = "class C { event Action a = () => { }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@23 -> [a = () => { }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_Reorder() { var src1 = "class C { int a = 0; int b = 1; int c = 2; }"; var src2 = "class C { int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int c = 2", FeaturesResources.field)); } [Fact] public void Field_Insert() { var src1 = "class C { }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a = 1;]@10", "Insert [int a = 1]@10", "Insert [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Insert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { this = default(S); a = z; } } "; var src2 = @" struct S { public int a; private int b; private static int c; private static int f = 1; private event System.Action d; public S(int z) { this = default(S); a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "b", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "c", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "f = 1", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "d", CSharpFeaturesResources.event_field, CSharpFeaturesResources.struct_)); } [Fact] public void Field_Insert_IntoLayoutClass_Auto() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.b")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.c")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.d")), }); } [Fact] public void Field_Insert_IntoLayoutClass_Explicit() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; [FieldOffset(0)] private int b; [FieldOffset(4)] private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void Field_Insert_ConstructorReplacingImplicitConstructor_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() // new ctor replacing existing implicit constructor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ParameterlessConstructorInsert_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersButNoExistingLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single()) }); } [Fact] public void Field_Insert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddStaticFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Insert_Static_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public static int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddInstanceFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add_NotSupportedByRuntime() { var src1 = @" class C { public int a = 1, x = 1; }"; var src2 = @" class C { [System.Obsolete]public int a = 1, x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public int a = 1, x = 1;]@18 -> [[System.Obsolete]public int a = 1, x = 1;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add() { var src1 = @" class C { public int a, b; }"; var src2 = @" class C { [System.Obsolete]public int a, b; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.b")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_Add_WithInitializer() { var src1 = @" class C { int a; }"; var src2 = @" class C { [System.Obsolete]int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_DeleteInsertUpdate_WithInitializer() { var srcA1 = "partial class C { int a = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { [System.Obsolete]int a = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Delete1() { var src1 = "class C { int a = 1; }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a = 1;]@10", "Delete [int a = 1]@10", "Delete [a = 1]@14"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void Field_UnsafeModifier_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node* left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [unsafe Node* left;]@14 -> [Node* left;]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_ModifierAndType_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe Node* left;]@14 -> [Node left;]@14", "Update [Node* left]@21 -> [Node left]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "Node left", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Event_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Event_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_), Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_)); } [Fact] public void Field_Type_Update_ReorderRemoveAdd() { var src1 = "class C { int F, G, H; bool U; }"; var src2 = "class C { string G, F; double V, U; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int F, G, H]@10 -> [string G, F]@10", "Reorder [G]@17 -> @17", "Update [bool U]@23 -> [double V, U]@23", "Insert [V]@30", "Delete [H]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "double V, U", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "string G, F", DeletedSymbolDisplay(FeaturesResources.field, "H"))); } [Fact] public void Field_Event_Reorder() { var src1 = "class C { int a = 0; int b = 1; event int c = 2; }"; var src2 = "class C { event int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "event int c = 2", CSharpFeaturesResources.event_field)); } [Fact] public void Field_Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E = 2; }"; var srcA2 = "partial class C { event int E = 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } #endregion #region Properties [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Property_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F => 0; }"; var src2 = "class C { " + newModifiers + "int F => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F => 0;]@10 -> [" + newModifiers + "int F => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Rename() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int Q => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Update() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [int P => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Property_ExpressionBody_ModifierUpdate() { var src1 = "class C { int P => 1; }"; var src2 = "class C { unsafe int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [unsafe int P => 1;]@10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ExpressionBodyToBlockBody1() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } }]@10", "Insert [{ get { return 2; } }]@16", "Insert [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_ExpressionBodyToBlockBody2() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } set { } }]@10", "Insert [{ get { return 2; } set { } }]@16", "Insert [get { return 2; }]@18", "Insert [set { }]@36"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody1() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } }]@16", "Delete [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody2() { var src1 = "class C { int P { get { return 2; } set { } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } set { } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } set { } }]@16", "Delete [get { return 2; }]@18", "Delete [set { }]@36"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get => 2; }]@10", "Insert [{ get => 2; }]@16", "Insert [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get => 2; }]@10 -> [int P => 1;]@10", "Delete [{ get => 2; }]@16", "Delete [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int P { set { } } }"; var src2 = "class C { int P { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@18 -> [set => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int P { init { } } }"; var src2 = "class C { int P { init => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@18 -> [init => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod, preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyWithSetterToGetterExpressionBodyWithSetter() { var src1 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyWithSetterToGetterBlockBodyWithSetter() { var src1 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_Rename1() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_Rename2() { var src1 = "class C { int I.P { get { return 1; } } }"; var src2 = "class C { int J.P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.P", FeaturesResources.property_)); } [Fact] public void Property_RenameAndUpdate() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyDelete() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.property_, "P"))); } [Fact] public void PropertyReorder1() { var src1 = "class C { int P { get { return 1; } } int Q { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get { return 1; } }]@38 -> @10"); // TODO: we can allow the move since the property doesn't have a backing field edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyReorder2() { var src1 = "class C { int P { get; set; } int Q { get; set; } }"; var src2 = "class C { int Q { get; set; } int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get; set; }]@30 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.auto_property)); } [Fact] public void PropertyAccessorReorder_GetSet() { var src1 = "class C { int P { get { return 1; } set { } } }"; var src2 = "class C { int P { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyAccessorReorder_GetInit() { var src1 = "class C { int P { get { return 1; } init { } } }"; var src2 = "class C { int P { init { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [init { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyTypeUpdate() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { char P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; set; }]@10 -> [char P { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "char P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "get", CSharpFeaturesResources.property_getter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyInsert() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("P"))); } [Fact] public void PropertyInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "int P", FeaturesResources.auto_property)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void PropertyInsert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { private static extern int P1 { [DllImport(""x.dll"")]get; } private static extern int P2 { [DllImport(""x.dll"")]set; } private static extern int P3 { [DllImport(""x.dll"")]get; [DllImport(""x.dll"")]set; } } "; var edits = GetTopEdits(src1, src2); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int P1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P3", FeaturesResources.property_)); } [Fact] public void PropertyInsert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { a = z; } } "; var src2 = @" struct S { public int a; private static int c { get; set; } private static int e { get { return 0; } set { } } private static int g { get; } = 1; private static int i { get; set; } = 1; private static int k => 1; public S(int z) { a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "private static int c { get; set; }", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int g { get; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_)); } [Fact] public void PropertyInsert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b { get; set; } private static int c { get; set; } private int d { get { return 0; } set { } } private static int e { get { return 0; } set { } } private int f { get; } = 1; private static int g { get; } = 1; private int h { get; set; } = 1; private static int i { get; set; } = 1; private int j => 1; private static int k => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int b { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int c { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int f { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int g { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int h { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_)); } // Design: Adding private accessors should also be allowed since we now allow adding private methods // and adding public properties and/or public accessors are not allowed. [Fact] public void PrivateProperty_AccessorAdd() { var src1 = "class C { int _p; int P { get { return 1; } } }"; var src2 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivatePropertyAccessorDelete() { var src1 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var src2 = "class C { int _p; int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorAdd1() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd2() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; private set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [private set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd4() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd5() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; internal set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [internal set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd6() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd_Init() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; init; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [init;]@23"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivateAutoPropertyAccessorDelete_Get() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_getter, "P.get"))); } [Fact] public void AutoPropertyAccessor_SetToInit() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set;]@23 -> [init;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "init", CSharpFeaturesResources.property_setter)); } [Fact] public void AutoPropertyAccessor_InitToSet() { var src1 = "class C { int P { get; init; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init;]@23 -> [set;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PrivateAutoPropertyAccessorDelete_Set() { var src1 = "class C { int P { get; set; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorDelete_Init() { var src1 = "class C { int P { get; init; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [init;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.init"))); } [Fact] public void AutoPropertyAccessorUpdate() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get;]@18 -> [set;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [WorkItem(992578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992578")] [Fact] public void InsertIncompleteProperty() { var src1 = "class C { }"; var src2 = "class C { public int P { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public int P { }]@10", "Insert [{ }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int P { get; }]@13", "Insert [{ get; }]@32", "Insert [get;]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Update() { var src1 = "class Test { int P { get; } }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; }]@13 -> [ref readonly int P { get; }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int P", FeaturesResources.property_)); } [Fact] public void Property_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get => 1; set { } } }"; var srcA2 = "partial class C { int P { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }), DocumentResults(), }); } [Fact] public void PropertyInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int Q { get => 1; init { } }}"; var srcA2 = "partial class C { int Q { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcA2 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod), }), DocumentResults(), }); } [Fact] public void AutoPropertyWithInitializer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } = 1; }"; var srcA2 = "partial class C { int P { get; set; } = 1; }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } [Fact] public void PropertyWithExpressionBody_Partial_InsertDeleteUpdate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P => 1; }"; var srcA2 = "partial class C { int P => 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_ReadOnly_Add() { var src1 = @" struct S { int P { get; } }"; var src2 = @" struct S { readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Property_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P1", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.property_setter)); } [Fact] public void Property_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P3").SetMethod, preserveLocalVariables: false) }); } #endregion #region Indexers [Theory] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Indexer_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int this[int a] => 0; }"; var src2 = "class C { " + newModifiers + "int this[int a] => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int this[int a] => 0;]@10 -> [" + newModifiers + "int this[int a] => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int this[int a]", FeaturesResources.indexer_)); } [Fact] public void Indexer_GetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [get { return 1; }]@28 -> [get { return 2; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_SetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set { System.Console.WriteLine(value); }]@46 -> [set { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_InitUpdate() { var src1 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init { System.Console.WriteLine(value); }]@46 -> [init { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void IndexerWithExpressionBody_Update() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)() + 10; } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)() + 11; // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)() + 10;]@35 -> [int this[int a] => new Func<int>(() => 2)() + 11;]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_2() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)();]@35 -> [int this[int a] => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_3() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(() => { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_4() { var src1 = @" using System; class C { int this[int a] => new Func<int>(delegate { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(delegate { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(delegate { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(delegate { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } }]@10", "Insert [{ get { return 1; } }]@26", "Insert [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } }]@26", "Delete [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get => 1; }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get => 1; }]@26", "Delete [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get => 1; }]@10", "Insert [{ get => 1; }]@26", "Insert [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int this[int a] { set { } } void F() { } }"; var src2 = "class C { int this[int a] { set => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@28 -> [set => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int this[int a] { init { } } void F() { } }"; var src2 = "class C { int this[int a] { init => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@28 -> [init => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterAndSetterBlockBodiesToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Delete [get { return 1; }]@28", "Delete [set { Console.WriteLine(0); }]@46"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterAndSetterBlockBodies() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10", "Insert [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Insert [get { return 1; }]@28", "Insert [set { Console.WriteLine(0); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_Rename() { var src1 = "class C { int I.this[int a] { get { return 1; } } }"; var src2 = "class C { int J.this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Indexer_Reorder1() { var src1 = "class C { int this[int a] { get { return 1; } } int this[string a] { get { return 1; } } }"; var src2 = "class C { int this[string a] { get { return 1; } } int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int this[string a] { get { return 1; } }]@48 -> @10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_AccessorReorder() { var src1 = "class C { int this[int a] { get { return 1; } set { } } }"; var src2 = "class C { int this[int a] { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@46 -> @28"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_TypeUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { string this[int a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get; set; }]@10 -> [string this[int a] { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Tuple_TypeUpdate() { var src1 = "class C { (int, int) M() { throw new System.Exception(); } }"; var src2 = "class C { (string, int) M() { throw new System.Exception(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { throw new System.Exception(); }]@10 -> [(string, int) M() { throw new System.Exception(); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(string, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementDelete() { var src1 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var src2 = "class C { (int, int) M() { return (1, 2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int, int a) M() { return (1, 2, 3); }]@10 -> [(int, int) M() { return (1, 2); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementAdd() { var src1 = "class C { (int, int) M() { return (1, 2); } }"; var src2 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { return (1, 2); }]@10 -> [(int, int, int a) M() { return (1, 2, 3); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int, int a) M()", FeaturesResources.method)); } [Fact] public void Indexer_ParameterUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { int this[string a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string a", FeaturesResources.parameter)); } [Fact] public void Indexer_AddGetAccessor() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [get { return arr[i]; }]@304"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "get", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_AddSetAccessor() { var src1 = @" class C { public int this[int i] { get { return default; } } }"; var src2 = @" class C { public int this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@67"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)); } [Fact] public void Indexer_AddSetAccessor_GenericType() { var src1 = @" class C<T> { public T this[int i] { get { return default; } } }"; var src2 = @" class C<T> { public T this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@68"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "set", CSharpFeaturesResources.indexer_setter)); } [WorkItem(750109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750109")] [Fact] public void Indexer_DeleteGetAccessor() { var src1 = @" class C<T> { public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var src2 = @" class C<T> { public T this[int i] { set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get { return arr[i]; }]@58"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public T this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_getter, "this[int i].get"))); } [Fact] public void Indexer_DeleteSetAccessor() { var src1 = @" class C { public int this[int i] { get { return 0; } set { } } }"; var src2 = @" class C { public int this[int i] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { }]@61"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public int this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int i].set"))); } [Fact, WorkItem(1174850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174850")] public void Indexer_Insert() { var src1 = "struct C { }"; var src2 = "struct C { public int this[int x, int y] { get { return x + y; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int this[in int i] => throw null;]@13", "Insert [[in int i]]@21", "Insert [in int i]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int i]@22 -> [in int i]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int i", FeaturesResources.parameter)); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int this[int i] => throw null;]@13", "Insert [[int i]]@34", "Insert [int i]@35"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int i] => throw null;]@13 -> [ref readonly int this[int i] => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int this[int i]", FeaturesResources.indexer_)); } [Fact] public void Indexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcA2 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void IndexerInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcA2 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoIndexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get; set; } }"; var srcA2 = "partial class C { int this[int x] { get; set; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod), }), DocumentResults(), }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Partial_InsertDeleteUpdate_LiftedParameter() { var srcA1 = @" partial class C { }"; var srcB1 = @" partial class C { int this[int a] => new System.Func<int>(() => a + 1); }"; var srcA2 = @" partial class C { int this[int a] => new System.Func<int>(() => 2); // no capture }"; var srcB2 = @" partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a") }), DocumentResults(), }); } [Fact] public void AutoIndexer_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get; } }"; var src2 = @" struct S { readonly int this[int x] { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.indexer_setter)); } [Fact] public void Indexer_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "UInt32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false) }); } #endregion #region Events [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Event_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "event Action F { add {} remove {} } }"; var src2 = "class C { " + newModifiers + "event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "event Action F { add {} remove {} }]@10 -> [" + newModifiers + "event Action F { add {} remove {} }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "event Action F", FeaturesResources.event_)); } [Fact] public void Event_Accessor_Reorder1() { var src1 = "class C { event int E { add { } remove { } } }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [remove { }]@32 -> @24"); edits.VerifyRudeDiagnostics(); } [Fact] public void Event_Accessor_Reorder2() { var src1 = "class C { event int E1 { add { } remove { } } event int E1 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E2 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event int E1 { add { } remove { } }]@10 -> [event int E2 { remove { } add { } }]@10", "Update [event int E1 { add { } remove { } }]@49 -> [event int E2 { remove { } add { } }]@49", "Reorder [remove { }]@33 -> @25", "Reorder [remove { }]@72 -> @64"); } [Fact] public void Event_Accessor_Reorder3() { var src1 = "class C { event int E1 { add { } remove { } } event int E2 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E1 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int E2 { add { } remove { } }]@49 -> @10", "Reorder [remove { }]@72 -> @25", "Reorder [remove { }]@33 -> @64"); } [Fact] public void Event_Insert() { var src1 = "class C { }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("E"))); } [Fact] public void Event_Delete() { var src1 = "class C { event int E { remove { } add { } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.event_, "E"))); } [Fact] public void Event_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { } "; var src2 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private event Action c { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_ExpressionBodyToBlockBody() { var src1 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add => F();]@57 -> [add { F(); }]@56", "Update [remove => F();]@69 -> [remove { }]@69" ); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_BlockBodyToExpressionBody() { var src1 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var src2 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add { F(); }]@56 -> [add => F();]@57", "Update [remove { }]@69 -> [remove => F();]@69" ); edits.VerifySemanticDiagnostics(); } [Fact] public void Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E { add { } remove { } } }"; var srcA2 = "partial class C { event int E { add { } remove { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod) }), DocumentResults(), }); } [Fact] public void Event_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { public event Action E { add {} remove {} } }"; var src2 = @" struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly event Action E", FeaturesResources.event_)); } [Fact] public void Event_InReadOnlyStruct_ReadOnly_Add1() { var src1 = @" readonly struct S { public event Action E { add {} remove {} } }"; var src2 = @" readonly struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough bodies nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").RemoveMethod)); } [Fact] public void Field_Event_Attribute_Add() { var src1 = @" class C { event Action F; }"; var src2 = @" class C { [System.Obsolete]event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F;]@18 -> [[System.Obsolete]event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F { add {} remove {} }]@18 -> [[System.Obsolete]event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [remove {}]@42 -> [[System.Obsolete]remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F; }"; var src2 = @" class C { event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F;]@18 -> [event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F { add {} remove {} }]@18 -> [event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Delete() { var src1 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]remove {}]@42 -> [remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Parameter [Fact] public void ParameterRename_Method1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterRename_Ctor1() { var src1 = @"class C { public C(int a) {} }"; var src2 = @"class C { public C(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@19 -> [int b]@19"); } [Fact] public void ParameterRename_Operator1() { var src1 = @"class C { public static implicit operator int(C a) {} }"; var src2 = @"class C { public static implicit operator int(C b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C a]@46 -> [C b]@46"); } [Fact] public void ParameterRename_Operator2() { var src1 = @"class C { public static int operator +(C a, C b) { return 0; } }"; var src2 = @"class C { public static int operator +(C a, C x) { return 0; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C b]@44 -> [C x]@44"); } [Fact] public void ParameterRename_Indexer2() { var src1 = @"class C { public int this[int a, int b] { get { return 0; } } }"; var src2 = @"class C { public int this[int a, int x] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@33 -> [int x]@33"); } [Fact] public void ParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@24"); } [Fact] public void ParameterInsert2() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int a, ref int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@23 -> [(int a, ref int b)]@23", "Insert [ref int b]@31"); } [Fact] public void ParameterDelete1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@24"); } [Fact] public void ParameterDelete2() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b)]@23 -> [(int b)]@23", "Delete [int a]@24"); } [Fact] public void ParameterUpdate() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterReorder() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24"); } [Fact] public void ParameterReorderAndUpdate() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int c) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24", "Update [int a]@24 -> [int c]@31"); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Parameter_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Parameter_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " a", FeaturesResources.parameter)); } [Fact] public void Parameter_Type_Nullable() { var src1 = @" #nullable enable class C { static void M(string a) { } } "; var src2 = @" #nullable disable class C { static void M(string a) { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("this")] [InlineData("ref")] [InlineData("out")] [InlineData("params")] public void Parameter_Modifier_Remove(string modifier) { var src1 = @"static class C { static void F(" + modifier + " int[] a) { } }"; var src2 = @"static class C { static void F(int[] a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "int[] a", FeaturesResources.parameter)); } [Theory] [InlineData("int a = 1", "int a = 2")] [InlineData("int a = 1", "int a")] [InlineData("int a", "int a = 2")] [InlineData("object a = null", "object a")] [InlineData("object a", "object a = null")] [InlineData("double a = double.NaN", "double a = 1.2")] public void Parameter_Initializer_Update(string oldParameter, string newParameter) { var src1 = @"static class C { static void F(" + oldParameter + ") { } }"; var src2 = @"static class C { static void F(" + newParameter + ") { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, newParameter, FeaturesResources.parameter)); } [Fact] public void Parameter_Initializer_NaN() { var src1 = @"static class C { static void F(double a = System.Double.NaN) { } }"; var src2 = @"static class C { static void F(double a = double.NaN) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Parameter_Initializer_InsertDeleteUpdate() { var srcA1 = @"partial class C { }"; var srcB1 = @"partial class C { public static void F(int x = 1) {} }"; var srcA2 = @"partial class C { public static void F(int x = 2) {} }"; var srcB2 = @"partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(), }); } [Fact] public void Parameter_Attribute_Insert() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@63 -> [[A]int a]@63"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_NonCustomAttribute() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M([System.Runtime.InteropServices.InAttribute]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [[System.Runtime.InteropServices.InAttribute]int a]@24"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute1() { var attribute = "public class AAttribute : System.Security.Permissions.SecurityAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@101 -> [[A]int a]@101"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute2() { var attribute = "public class BAttribute : System.Security.Permissions.SecurityAttribute { }\n\n" + "public class AAttribute : BAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@143 -> [[A]int a]@143"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@72 -> [[A]int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M([A, B]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@120 -> [[A, B]int a]@120"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Delete_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@72 -> [int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([System.Obsolete(""1""), B]int a) {} }"; var src2 = attribute + @"class C { public void M([System.Obsolete(""2""), A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]int a]@120 -> [[System.Obsolete(\"2\"), A]int a]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) {} }"; var src2 = attribute + "class C { void F([A(1)]int a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) { F(0); } }"; var src2 = attribute + "class C { void F([A(1)]int a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F([A(0)]int a) { F(0); }]@60 -> [void F([A(1)]int a) { F(1); }]@60", "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Method Type Parameter [Fact] public void MethodTypeParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M<A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@23", "Insert [A]@24"); } [Fact] public void MethodTypeParameterInsert2() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<A,B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@23 -> [<A,B>]@23", "Insert [B]@26"); } [Fact] public void MethodTypeParameterDelete1() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterDelete2() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@23 -> [<B>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterUpdate() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@24 -> [B]@24"); } [Fact] public void MethodTypeParameterReorder() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24"); } [Fact] public void MethodTypeParameterReorderAndUpdate() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,C>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24", "Update [A]@24 -> [C]@26"); } [Fact] public void MethodTypeParameter_Attribute_Insert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<T>() {} }"; var src2 = attribute + @"class C { public void M<[A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@72 -> [[A]T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Insert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<[A, B]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@120 -> [[A, B]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@72 -> [T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[System.Obsolete(""1""), B]T>() {} }"; var src2 = attribute + @"class C { public void M<[System.Obsolete(""2""), A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@120 -> [[System.Obsolete(\"2\"), A]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) {} }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) { F(0); } }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F<[A(0)]T>(T a) { F(0); }]@60 -> [void F<[A(1)]T>(T a) { F(1); }]@60", "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<[A(1)]T>(T a)"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } #endregion #region Type Type Parameter [Fact] public void TypeTypeParameterInsert1() { var src1 = @"class C {}"; var src2 = @"class C<A> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@7", "Insert [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "A", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterInsert2() { var src1 = @"class C<A> {}"; var src2 = @"class C<A,B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@7 -> [<A,B>]@7", "Insert [B]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterDelete1() { var src1 = @"class C<A> { }"; var src2 = @"class C { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@7", "Delete [A]@8"); } [Fact] public void TypeTypeParameterDelete2() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@7 -> [<B>]@7", "Delete [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<B>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "A"))); } [Fact] public void TypeTypeParameterUpdate() { var src1 = @"class C<A> {}"; var src2 = @"class C<B> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@8 -> [B]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "B")); } [Fact] public void TypeTypeParameterReorder() { var src1 = @"class C<A,B> { }"; var src2 = @"class C<B,A> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterReorderAndUpdate() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B,C> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8", "Update [A]@8 -> [C]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.Renamed, "C", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "C")); } [Fact] public void TypeTypeParameterAttributeInsert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<[A, B]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@104 -> [[A, B]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert_SupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeDelete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@56 -> [T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeUpdate() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[System.Obsolete(""1""), B]T> {}"; var src2 = attribute + @"class C<[System.Obsolete(""2""), A]T> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@104 -> [[System.Obsolete(\"2\"), A]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple_Reloadable() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Type Parameter Constraints [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Insert(string newConstraint) { var src1 = "class C<S,T> { }"; var src2 = "class C<S,T> where T : " + newConstraint + " { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where T : " + newConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : " + newConstraint, FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : " + newConstraint)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Delete(string oldConstraint) { var src1 = "class C<S,T> where T : " + oldConstraint + " { }"; var src2 = "class C<S,T> { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where T : " + oldConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Theory] [InlineData("string", "string?")] [InlineData("(int a, int b)", "(int a, int c)")] public void TypeConstraint_Update_RuntimeTypeUnchanged(string oldType, string newType) { // note: dynamic is not allowed in constraints var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void TypeConstraint_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : System.Collections.Generic.List<" + newType + ">", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Fact] public void TypeConstraint_Delete_WithParameter() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S> where S : new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<S>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void TypeConstraint_MultipleClauses_Insert() { var src1 = "class C<S,T> where T : class { }"; var src2 = "class C<S,T> where S : unmanaged where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where S : unmanaged]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where S : unmanaged", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : unmanaged")); } [Fact] public void TypeConstraint_MultipleClauses_Delete() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S,T> where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where S : new()]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void TypeConstraint_MultipleClauses_Reorder() { var src1 = "class C<S,T> where S : struct where T : class { }"; var src2 = "class C<S,T> where T : class where S : struct { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@30 -> @13"); edits.VerifyRudeDiagnostics(); } [Fact] public void TypeConstraint_MultipleClauses_UpdateAndReorder() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<T,S> where T : class, I where S : class, new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@29 -> @13", "Reorder [T]@10 -> @8", "Update [where T : class]@29 -> [where T : class, I]@13", "Update [where S : new()]@13 -> [where S : class, new()]@32"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingConstraints, "where T : class, I", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : class, I"), Diagnostic(RudeEditKind.ChangingConstraints, "where S : class, new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : class, new()")); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_Update() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_InsertAndUpdate() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); Console.WriteLine(""What is your name?""); var name = Console.ReadLine(); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19", "Insert [Console.WriteLine(\"What is your name?\");]@54", "Insert [var name = Console.ReadLine();]@96"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_NoImplicitMain() { var src1 = @" using System; "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Delete_NoImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello World""); "; var src2 = @" using System; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"Hello World\");]@19"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_Delete_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var src2 = @" using System; Console.WriteLine(""Hello""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_StackAlloc() { var src1 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(1); }"; var src2 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_VoidToInt1() { var src1 = @" using System; Console.Write(1); "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt2() { var src1 = @" using System; Console.Write(1); return; "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt3() { var src1 = @" using System; Console.Write(1); int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_AddAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_DeleteAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_VoidToTask() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "await Task.Delay(100);")); } [Fact] public void TopLevelStatements_TaskToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return await GetInt();")); } [Fact] public void TopLevelStatements_IntToVoid1() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_IntToVoid2() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); return; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return;")); } [Fact] public void TopLevelStatements_IntToVoid3() { var src1 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "int Goo()\r\n{\r\n return 1;\r\n}")); } [Fact] public void TopLevelStatements_IntToVoid4() { var src1 = @" using System; Console.Write(1); return 1; public class C { public int Goo() { return 1; } } "; var src2 = @" using System; Console.Write(1); public class C { public int Goo() { return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskToVoid() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_TaskIntToTask() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskIntToVoid() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_WithLambda_Insert() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Update() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(2); public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Delete() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_UpdateMultiple() { var src1 = @" using System; Console.WriteLine(1); Console.WriteLine(2); public class C { } "; var src2 = @" using System; Console.WriteLine(3); Console.WriteLine(4); public class C { } "; var edits = GetTopEdits(src1, src2); // Since each individual statement is a separate update to a separate node, this just validates we correctly // only analyze the things once edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_MoveToOtherFile() { var srcA1 = @" using System; Console.WriteLine(1); public class A { }"; var srcB1 = @" using System; public class B { }"; var srcA2 = @" using System; public class A { }"; var srcB2 = @" using System; Console.WriteLine(2); public class B { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new [] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")) }), }); } #endregion } }
1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/Workspace/Host/Mef/ExportLanguageServiceFactoryAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// Use this attribute to declare a <see cref="ILanguageServiceFactory"/> implementation for inclusion in a MEF-based workspace. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public class ExportLanguageServiceFactoryAttribute : ExportAttribute { /// <summary> /// The assembly qualified name of the service's type. /// </summary> public string ServiceType { get; } /// <summary> /// The language that the service is target for; LanguageNames.CSharp, etc. /// </summary> public string Language { get; } /// <summary> /// The layer that the service is specified for; ServiceLayer.Default, etc. /// </summary> public string Layer { get; } /// <summary> /// Declares a <see cref="ILanguageServiceFactory"/> implementation for inclusion in a MEF-based workspace. /// </summary> /// <param name="type">The type that will be used to retrieve the service from a <see cref="HostLanguageServices"/>.</param> /// <param name="language">The language that the service is target for; LanguageNames.CSharp, etc.</param> /// <param name="layer">The layer that the service is specified for; ServiceLayer.Default, etc.</param> public ExportLanguageServiceFactoryAttribute(Type type, string language, string layer = ServiceLayer.Default) : base(typeof(ILanguageServiceFactory)) { if (type == null) { throw new ArgumentNullException(nameof(type)); } this.ServiceType = type.AssemblyQualifiedName; this.Language = language ?? throw new ArgumentNullException(nameof(language)); this.Layer = layer; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// Use this attribute to declare a <see cref="ILanguageServiceFactory"/> implementation for inclusion in a MEF-based workspace. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public class ExportLanguageServiceFactoryAttribute : ExportAttribute { /// <summary> /// The assembly qualified name of the service's type. /// </summary> public string ServiceType { get; } /// <summary> /// The language that the service is target for; LanguageNames.CSharp, etc. /// </summary> public string Language { get; } /// <summary> /// The layer that the service is specified for; ServiceLayer.Default, etc. /// </summary> public string Layer { get; } /// <summary> /// Declares a <see cref="ILanguageServiceFactory"/> implementation for inclusion in a MEF-based workspace. /// </summary> /// <param name="type">The type that will be used to retrieve the service from a <see cref="HostLanguageServices"/>.</param> /// <param name="language">The language that the service is target for; LanguageNames.CSharp, etc.</param> /// <param name="layer">The layer that the service is specified for; ServiceLayer.Default, etc.</param> public ExportLanguageServiceFactoryAttribute(Type type, string language, string layer = ServiceLayer.Default) : base(typeof(ILanguageServiceFactory)) { if (type == null) { throw new ArgumentNullException(nameof(type)); } this.ServiceType = type.AssemblyQualifiedName; this.Language = language ?? throw new ArgumentNullException(nameof(language)); this.Layer = layer; } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Remote/ServiceHub/Services/InheritanceMargin/RemoteInheritanceMarginService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.InheritanceMargin; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteInheritanceMarginService : BrokeredServiceBase, IRemoteInheritanceMarginService { internal sealed class Factory : FactoryBase<IRemoteInheritanceMarginService> { protected override IRemoteInheritanceMarginService CreateService(in ServiceConstructionArguments arguments) { return new RemoteInheritanceMarginService(arguments); } } public RemoteInheritanceMarginService(in ServiceConstructionArguments arguments) : base(in arguments) { } public ValueTask<ImmutableArray<SerializableInheritanceMarginItem>> GetInheritanceMarginItemsAsync( PinnedSolutionInfo pinnedSolutionInfo, ProjectId projectId, ImmutableArray<(SymbolKey symbolKey, int lineNumber)> symbolKeyAndLineNumbers, CancellationToken cancellationToken) => RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(pinnedSolutionInfo, cancellationToken).ConfigureAwait(false); return await InheritanceMarginServiceHelper .GetInheritanceMemberItemAsync(solution, projectId, symbolKeyAndLineNumbers, 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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.InheritanceMargin; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteInheritanceMarginService : BrokeredServiceBase, IRemoteInheritanceMarginService { internal sealed class Factory : FactoryBase<IRemoteInheritanceMarginService> { protected override IRemoteInheritanceMarginService CreateService(in ServiceConstructionArguments arguments) { return new RemoteInheritanceMarginService(arguments); } } public RemoteInheritanceMarginService(in ServiceConstructionArguments arguments) : base(in arguments) { } public ValueTask<ImmutableArray<SerializableInheritanceMarginItem>> GetInheritanceMarginItemsAsync( PinnedSolutionInfo pinnedSolutionInfo, ProjectId projectId, ImmutableArray<(SymbolKey symbolKey, int lineNumber)> symbolKeyAndLineNumbers, CancellationToken cancellationToken) => RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(pinnedSolutionInfo, cancellationToken).ConfigureAwait(false); return await InheritanceMarginServiceHelper .GetInheritanceMemberItemAsync(solution, projectId, symbolKeyAndLineNumbers, cancellationToken) .ConfigureAwait(false); }, cancellationToken); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Core/Portable/InternalUtilities/RoslynParallel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal static class RoslynParallel { internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions(); /// <inheritdoc cref="Parallel.For(int, int, ParallelOptions, Action{int})"/> public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body, CancellationToken cancellationToken) { var parallelOptions = cancellationToken.CanBeCanceled ? new ParallelOptions { CancellationToken = cancellationToken } : DefaultParallelOptions; return Parallel.For(fromInclusive, toExclusive, parallelOptions, errorHandlingBody); // Local function void errorHandlingBody(int i) { try { body(i); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } catch (OperationCanceledException e) when (cancellationToken.IsCancellationRequested && e.CancellationToken != cancellationToken) { // Parallel.For checks for a specific cancellation token, so make sure we throw with the // correct one. cancellationToken.ThrowIfCancellationRequested(); 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal static class RoslynParallel { internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions(); /// <inheritdoc cref="Parallel.For(int, int, ParallelOptions, Action{int})"/> public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body, CancellationToken cancellationToken) { var parallelOptions = cancellationToken.CanBeCanceled ? new ParallelOptions { CancellationToken = cancellationToken } : DefaultParallelOptions; return Parallel.For(fromInclusive, toExclusive, parallelOptions, errorHandlingBody); // Local function void errorHandlingBody(int i) { try { body(i); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } catch (OperationCanceledException e) when (cancellationToken.IsCancellationRequested && e.CancellationToken != cancellationToken) { // Parallel.For checks for a specific cancellation token, so make sure we throw with the // correct one. cancellationToken.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; } } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/CoreTest/CodeCleanup/ReduceTokenTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeCleanup.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup { [UseExportProvider] public class ReduceTokenTests { #if NETCOREAPP private static bool IsNetCoreApp => true; #else private static bool IsNetCoreApp => false; #endif [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_LessThan8Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 8 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 5 significant digits Const f_5_1 As Single = .14995F ' Dev11 & Roslyn: Pretty listed to 0.14995F Const f_5_2 As Single = 0.14995f ' Dev11 & Roslyn: Unchanged Const f_5_3 As Single = 1.4995F ' Dev11 & Roslyn: Unchanged Const f_5_4 As Single = 149.95f ' Dev11 & Roslyn: Unchanged Const f_5_5 As Single = 1499.5F ' Dev11 & Roslyn: Unchanged Const f_5_6 As Single = 14995.0f ' Dev11 & Roslyn: Unchanged ' 7 significant digits Const f_7_1 As Single = .1499995F ' Dev11 & Roslyn: Pretty listed to 0.1499995F Const f_7_2 As Single = 0.1499995f ' Dev11 & Roslyn: Unchanged Const f_7_3 As Single = 1.499995F ' Dev11 & Roslyn: Unchanged Const f_7_4 As Single = 1499.995f ' Dev11 & Roslyn: Unchanged Const f_7_5 As Single = 149999.5F ' Dev11 & Roslyn: Unchanged Const f_7_6 As Single = 1499995.0f ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_5_1) Console.WriteLine(f_5_2) Console.WriteLine(f_5_3) Console.WriteLine(f_5_4) Console.WriteLine(f_5_5) Console.WriteLine(f_5_6) Console.WriteLine(f_7_1) Console.WriteLine(f_7_2) Console.WriteLine(f_7_3) Console.WriteLine(f_7_4) Console.WriteLine(f_7_5) Console.WriteLine(f_7_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 8 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 5 significant digits Const f_5_1 As Single = 0.14995F ' Dev11 & Roslyn: Pretty listed to 0.14995F Const f_5_2 As Single = 0.14995F ' Dev11 & Roslyn: Unchanged Const f_5_3 As Single = 1.4995F ' Dev11 & Roslyn: Unchanged Const f_5_4 As Single = 149.95F ' Dev11 & Roslyn: Unchanged Const f_5_5 As Single = 1499.5F ' Dev11 & Roslyn: Unchanged Const f_5_6 As Single = 14995.0F ' Dev11 & Roslyn: Unchanged ' 7 significant digits Const f_7_1 As Single = 0.1499995F ' Dev11 & Roslyn: Pretty listed to 0.1499995F Const f_7_2 As Single = 0.1499995F ' Dev11 & Roslyn: Unchanged Const f_7_3 As Single = 1.499995F ' Dev11 & Roslyn: Unchanged Const f_7_4 As Single = 1499.995F ' Dev11 & Roslyn: Unchanged Const f_7_5 As Single = 149999.5F ' Dev11 & Roslyn: Unchanged Const f_7_6 As Single = 1499995.0F ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_5_1) Console.WriteLine(f_5_2) Console.WriteLine(f_5_3) Console.WriteLine(f_5_4) Console.WriteLine(f_5_5) Console.WriteLine(f_5_6) Console.WriteLine(f_7_1) Console.WriteLine(f_7_2) Console.WriteLine(f_7_3) Console.WriteLine(f_7_4) Console.WriteLine(f_7_5) Console.WriteLine(f_7_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_LessThan8Digits_WithTypeCharacterSingle() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 8 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 5 significant digits Const f_5_1 As Single = .14995! ' Dev11 & Roslyn: Pretty listed to 0.14995! Const f_5_2 As Single = 0.14995! ' Dev11 & Roslyn: Unchanged Const f_5_3 As Single = 1.4995! ' Dev11 & Roslyn: Unchanged Const f_5_4 As Single = 149.95! ' Dev11 & Roslyn: Unchanged Const f_5_5 As Single = 1499.5! ' Dev11 & Roslyn: Unchanged Const f_5_6 As Single = 14995.0! ' Dev11 & Roslyn: Unchanged ' 7 significant digits Const f_7_1 As Single = .1499995! ' Dev11 & Roslyn: Pretty listed to 0.1499995! Const f_7_2 As Single = 0.1499995! ' Dev11 & Roslyn: Unchanged Const f_7_3 As Single = 1.499995! ' Dev11 & Roslyn: Unchanged Const f_7_4 As Single = 1499.995! ' Dev11 & Roslyn: Unchanged Const f_7_5 As Single = 149999.5! ' Dev11 & Roslyn: Unchanged Const f_7_6 As Single = 1499995.0! ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_5_1) Console.WriteLine(f_5_2) Console.WriteLine(f_5_3) Console.WriteLine(f_5_4) Console.WriteLine(f_5_5) Console.WriteLine(f_5_6) Console.WriteLine(f_7_1) Console.WriteLine(f_7_2) Console.WriteLine(f_7_3) Console.WriteLine(f_7_4) Console.WriteLine(f_7_5) Console.WriteLine(f_7_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 8 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 5 significant digits Const f_5_1 As Single = 0.14995! ' Dev11 & Roslyn: Pretty listed to 0.14995! Const f_5_2 As Single = 0.14995! ' Dev11 & Roslyn: Unchanged Const f_5_3 As Single = 1.4995! ' Dev11 & Roslyn: Unchanged Const f_5_4 As Single = 149.95! ' Dev11 & Roslyn: Unchanged Const f_5_5 As Single = 1499.5! ' Dev11 & Roslyn: Unchanged Const f_5_6 As Single = 14995.0! ' Dev11 & Roslyn: Unchanged ' 7 significant digits Const f_7_1 As Single = 0.1499995! ' Dev11 & Roslyn: Pretty listed to 0.1499995! Const f_7_2 As Single = 0.1499995! ' Dev11 & Roslyn: Unchanged Const f_7_3 As Single = 1.499995! ' Dev11 & Roslyn: Unchanged Const f_7_4 As Single = 1499.995! ' Dev11 & Roslyn: Unchanged Const f_7_5 As Single = 149999.5! ' Dev11 & Roslyn: Unchanged Const f_7_6 As Single = 1499995.0! ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_5_1) Console.WriteLine(f_5_2) Console.WriteLine(f_5_3) Console.WriteLine(f_5_4) Console.WriteLine(f_5_5) Console.WriteLine(f_5_6) Console.WriteLine(f_7_1) Console.WriteLine(f_7_2) Console.WriteLine(f_7_3) Console.WriteLine(f_7_4) Console.WriteLine(f_7_5) Console.WriteLine(f_7_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_8Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits Const f_8_1 As Single = .14999795F ' Dev11 & Roslyn: 0.14999795F Const f_8_2 As Single = .14999797f ' Dev11 & Roslyn: 0.149997965F Const f_8_3 As Single = 0.1499797F ' Dev11 & Roslyn: Unchanged Const f_8_4 As Single = 1.4999794f ' Dev11 & Roslyn: 1.49997938F Const f_8_5 As Single = 1.4999797F ' Dev11 & Roslyn: 1.49997973F Const f_8_6 As Single = 1499.9794f ' Dev11 & Roslyn: 1499.97937F Const f_8_7 As Single = 1499979.7F ' Dev11 & Roslyn: 1499979.75F Const f_8_8 As Single = 14999797.0F ' Dev11 & Roslyn: unchanged Console.WriteLine(f_8_1) Console.WriteLine(f_8_2) Console.WriteLine(f_8_3) Console.WriteLine(f_8_4) Console.WriteLine(f_8_5) Console.WriteLine(f_8_6) Console.WriteLine(f_8_7) Console.WriteLine(f_8_8) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 2: 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits Const f_8_1 As Single = 0.14999795F ' Dev11 & Roslyn: 0.14999795F Const f_8_2 As Single = {(IsNetCoreApp ? "0.14999796F" : "0.149997965F")} ' Dev11 & Roslyn: 0.149997965F Const f_8_3 As Single = 0.1499797F ' Dev11 & Roslyn: Unchanged Const f_8_4 As Single = {(IsNetCoreApp ? "1.4999794F" : "1.49997938F")} ' Dev11 & Roslyn: 1.49997938F Const f_8_5 As Single = {(IsNetCoreApp ? "1.4999797F" : "1.49997973F")} ' Dev11 & Roslyn: 1.49997973F Const f_8_6 As Single = {(IsNetCoreApp ? "1499.9794F" : "1499.97937F")} ' Dev11 & Roslyn: 1499.97937F Const f_8_7 As Single = {(IsNetCoreApp ? "1499979.8F" : "1499979.75F")} ' Dev11 & Roslyn: 1499979.75F Const f_8_8 As Single = 14999797.0F ' Dev11 & Roslyn: unchanged Console.WriteLine(f_8_1) Console.WriteLine(f_8_2) Console.WriteLine(f_8_3) Console.WriteLine(f_8_4) Console.WriteLine(f_8_5) Console.WriteLine(f_8_6) Console.WriteLine(f_8_7) Console.WriteLine(f_8_8) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_8Digits_WithTypeCharacterSingle() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits Const f_8_1 As Single = .14999795! ' Dev11 & Roslyn: 0.14999795F Const f_8_2 As Single = .14999797! ' Dev11 & Roslyn: 0.149997965F Const f_8_3 As Single = 0.1499797! ' Dev11 & Roslyn: Unchanged Const f_8_4 As Single = 1.4999794! ' Dev11 & Roslyn: 1.49997938F Const f_8_5 As Single = 1.4999797! ' Dev11 & Roslyn: 1.49997973F Const f_8_6 As Single = 1499.9794! ' Dev11 & Roslyn: 1499.97937F Const f_8_7 As Single = 1499979.7! ' Dev11 & Roslyn: 1499979.75F Const f_8_8 As Single = 14999797.0! ' Dev11 & Roslyn: unchanged Console.WriteLine(f_8_1) Console.WriteLine(f_8_2) Console.WriteLine(f_8_3) Console.WriteLine(f_8_4) Console.WriteLine(f_8_5) Console.WriteLine(f_8_6) Console.WriteLine(f_8_7) Console.WriteLine(f_8_8) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 2: 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits Const f_8_1 As Single = 0.14999795! ' Dev11 & Roslyn: 0.14999795F Const f_8_2 As Single = {(IsNetCoreApp ? "0.14999796!" : "0.149997965!")} ' Dev11 & Roslyn: 0.149997965F Const f_8_3 As Single = 0.1499797! ' Dev11 & Roslyn: Unchanged Const f_8_4 As Single = {(IsNetCoreApp ? "1.4999794!" : "1.49997938!")} ' Dev11 & Roslyn: 1.49997938F Const f_8_5 As Single = {(IsNetCoreApp ? "1.4999797!" : "1.49997973!")} ' Dev11 & Roslyn: 1.49997973F Const f_8_6 As Single = {(IsNetCoreApp ? "1499.9794!" : "1499.97937!")} ' Dev11 & Roslyn: 1499.97937F Const f_8_7 As Single = {(IsNetCoreApp ? "1499979.8!" : "1499979.75!")} ' Dev11 & Roslyn: 1499979.75F Const f_8_8 As Single = 14999797.0! ' Dev11 & Roslyn: unchanged Console.WriteLine(f_8_1) Console.WriteLine(f_8_2) Console.WriteLine(f_8_3) Console.WriteLine(f_8_4) Console.WriteLine(f_8_5) Console.WriteLine(f_8_6) Console.WriteLine(f_8_7) Console.WriteLine(f_8_8) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_GreaterThan8Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 3: > 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits ' (a) > 8 significant digits overall, but < 8 digits before decimal point. Const f_9_1 As Single = .149997938F ' Dev11 & Roslyn: 0.149997935F Const f_9_2 As Single = 0.149997931f ' Dev11 & Roslyn: 0.149997935F Const f_9_3 As Single = 1.49997965F ' Dev11 & Roslyn: 1.49997962F Const f_10_1 As Single = 14999.79652f ' Dev11 & Roslyn: 14999.7969F ' (b) > 8 significant digits before decimal point. Const f_10_2 As Single = 149997965.2F ' Dev11 & Roslyn: 149997968.0F Const f_10_3 As Single = 1499979652.0f ' Dev11 & Roslyn: 1.49997965E+9F Const f_24_1 As Single = 111111149999124689999.499F ' Dev11 & Roslyn: 1.11111148E+20F ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and ' from 1.401298E-45 through 3.4028235E+38 for positive values. Const f_overflow_1 As Single = -3.4028235E+39F ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Single = 3.4028235E+39F ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Single = -1.401298E-47F ' Dev11: -0.0F, Roslyn: Unchanged Const f_underflow_2 As Single = 1.401298E-47F ' Dev11: 0.0F, Roslyn: Unchanged Console.WriteLine(f_9_1) Console.WriteLine(f_9_2) Console.WriteLine(f_9_3) Console.WriteLine(f_10_1) Console.WriteLine(f_10_2) Console.WriteLine(f_10_3) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 3: > 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits ' (a) > 8 significant digits overall, but < 8 digits before decimal point. Const f_9_1 As Single = {(IsNetCoreApp ? "0.14999793F" : "0.149997935F")} ' Dev11 & Roslyn: 0.149997935F Const f_9_2 As Single = {(IsNetCoreApp ? "0.14999793F" : "0.149997935F")} ' Dev11 & Roslyn: 0.149997935F Const f_9_3 As Single = {(IsNetCoreApp ? "1.4999796F" : "1.49997962F")} ' Dev11 & Roslyn: 1.49997962F Const f_10_1 As Single = {(IsNetCoreApp ? "14999.797F" : "14999.7969F")} ' Dev11 & Roslyn: 14999.7969F ' (b) > 8 significant digits before decimal point. Const f_10_2 As Single = {(IsNetCoreApp ? "149997970.0F" : "149997968.0F")} ' Dev11 & Roslyn: 149997968.0F Const f_10_3 As Single = {(IsNetCoreApp ? "1.4999796E+9F" : "1.49997965E+9F")} ' Dev11 & Roslyn: 1.49997965E+9F Const f_24_1 As Single = {(IsNetCoreApp ? "1.1111115E+20F" : "1.11111148E+20F")} ' Dev11 & Roslyn: 1.11111148E+20F ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and ' from 1.401298E-45 through 3.4028235E+38 for positive values. Const f_overflow_1 As Single = -3.4028235E+39F ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Single = 3.4028235E+39F ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Single = -1.401298E-47F ' Dev11: -0.0F, Roslyn: Unchanged Const f_underflow_2 As Single = 1.401298E-47F ' Dev11: 0.0F, Roslyn: Unchanged Console.WriteLine(f_9_1) Console.WriteLine(f_9_2) Console.WriteLine(f_9_3) Console.WriteLine(f_10_1) Console.WriteLine(f_10_2) Console.WriteLine(f_10_3) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_GreaterThan8Digits_WithTypeCharacterSingle() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 3: > 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits ' (a) > 8 significant digits overall, but < 8 digits before decimal point. Const f_9_1 As Single = .149997938! ' Dev11 & Roslyn: 0.149997935F Const f_9_2 As Single = 0.149997931! ' Dev11 & Roslyn: 0.149997935F Const f_9_3 As Single = 1.49997965! ' Dev11 & Roslyn: 1.49997962F Const f_10_1 As Single = 14999.79652! ' Dev11 & Roslyn: 14999.7969F ' (b) > 8 significant digits before decimal point. Const f_10_2 As Single = 149997965.2! ' Dev11 & Roslyn: 149997968.0F Const f_10_3 As Single = 1499979652.0! ' Dev11 & Roslyn: 1.49997965E+9F Const f_24_1 As Single = 111111149999124689999.499! ' Dev11 & Roslyn: 1.11111148E+20F ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and ' from 1.401298E-45 through 3.4028235E+38 for positive values. Const f_overflow_1 As Single = -3.4028235E+39! ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Single = 3.4028235E+39! ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Single = -1.401298E-47! ' Dev11: -0.0F, Roslyn: Unchanged Const f_underflow_2 As Single = 1.401298E-47! ' Dev11: 0.0F, Roslyn: Unchanged Console.WriteLine(f_9_1) Console.WriteLine(f_9_2) Console.WriteLine(f_9_3) Console.WriteLine(f_10_1) Console.WriteLine(f_10_2) Console.WriteLine(f_10_3) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 3: > 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits ' (a) > 8 significant digits overall, but < 8 digits before decimal point. Const f_9_1 As Single = {(IsNetCoreApp ? "0.14999793!" : "0.149997935!")} ' Dev11 & Roslyn: 0.149997935F Const f_9_2 As Single = {(IsNetCoreApp ? "0.14999793!" : "0.149997935!")} ' Dev11 & Roslyn: 0.149997935F Const f_9_3 As Single = {(IsNetCoreApp ? "1.4999796!" : "1.49997962!")} ' Dev11 & Roslyn: 1.49997962F Const f_10_1 As Single = {(IsNetCoreApp ? "14999.797!" : "14999.7969!")} ' Dev11 & Roslyn: 14999.7969F ' (b) > 8 significant digits before decimal point. Const f_10_2 As Single = {(IsNetCoreApp ? "149997970.0!" : "149997968.0!")} ' Dev11 & Roslyn: 149997968.0F Const f_10_3 As Single = {(IsNetCoreApp ? "1.4999796E+9!" : "1.49997965E+9!")} ' Dev11 & Roslyn: 1.49997965E+9F Const f_24_1 As Single = {(IsNetCoreApp ? "1.1111115E+20!" : "1.11111148E+20!")} ' Dev11 & Roslyn: 1.11111148E+20F ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and ' from 1.401298E-45 through 3.4028235E+38 for positive values. Const f_overflow_1 As Single = -3.4028235E+39! ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Single = 3.4028235E+39! ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Single = -1.401298E-47! ' Dev11: -0.0F, Roslyn: Unchanged Const f_underflow_2 As Single = 1.401298E-47! ' Dev11: 0.0F, Roslyn: Unchanged Console.WriteLine(f_9_1) Console.WriteLine(f_9_2) Console.WriteLine(f_9_3) Console.WriteLine(f_10_1) Console.WriteLine(f_10_2) Console.WriteLine(f_10_3) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_LessThan16Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 16 significant digits precision, ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 13 significant digits Const f_13_1 As Double = .1499599999999 ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 Const f_13_2 As Double = 0.149959999999 ' Dev11 & Roslyn: Unchanged Const f_13_3 As Double = 1.499599999999 ' Dev11 & Roslyn: Unchanged Const f_13_4 As Double = 1499599.999999 ' Dev11 & Roslyn: Unchanged Const f_13_5 As Double = 149959999999.9 ' Dev11 & Roslyn: Unchanged Const f_13_6 As Double = 1499599999999.0 ' Dev11 & Roslyn: Unchanged ' 15 significant digits Const f_15_1 As Double = .149999999999995 ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 Const f_15_2 As Double = 0.14999999999995 ' Dev11 & Roslyn: Unchanged Const f_15_3 As Double = 1.49999999999995 ' Dev11 & Roslyn: Unchanged Const f_15_4 As Double = 14999999.9999995 ' Dev11 & Roslyn: Unchanged Const f_15_5 As Double = 14999999999999.5 ' Dev11 & Roslyn: Unchanged Const f_15_6 As Double = 149999999999995.0 ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_13_1) Console.WriteLine(f_13_2) Console.WriteLine(f_13_3) Console.WriteLine(f_13_4) Console.WriteLine(f_13_5) Console.WriteLine(f_13_6) Console.WriteLine(f_15_1) Console.WriteLine(f_15_2) Console.WriteLine(f_15_3) Console.WriteLine(f_15_4) Console.WriteLine(f_15_5) Console.WriteLine(f_15_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 16 significant digits precision, ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 13 significant digits Const f_13_1 As Double = 0.1499599999999 ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 Const f_13_2 As Double = 0.149959999999 ' Dev11 & Roslyn: Unchanged Const f_13_3 As Double = 1.499599999999 ' Dev11 & Roslyn: Unchanged Const f_13_4 As Double = 1499599.999999 ' Dev11 & Roslyn: Unchanged Const f_13_5 As Double = 149959999999.9 ' Dev11 & Roslyn: Unchanged Const f_13_6 As Double = 1499599999999.0 ' Dev11 & Roslyn: Unchanged ' 15 significant digits Const f_15_1 As Double = 0.149999999999995 ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 Const f_15_2 As Double = 0.14999999999995 ' Dev11 & Roslyn: Unchanged Const f_15_3 As Double = 1.49999999999995 ' Dev11 & Roslyn: Unchanged Const f_15_4 As Double = 14999999.9999995 ' Dev11 & Roslyn: Unchanged Const f_15_5 As Double = 14999999999999.5 ' Dev11 & Roslyn: Unchanged Const f_15_6 As Double = 149999999999995.0 ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_13_1) Console.WriteLine(f_13_2) Console.WriteLine(f_13_3) Console.WriteLine(f_13_4) Console.WriteLine(f_13_5) Console.WriteLine(f_13_6) Console.WriteLine(f_15_1) Console.WriteLine(f_15_2) Console.WriteLine(f_15_3) Console.WriteLine(f_15_4) Console.WriteLine(f_15_5) Console.WriteLine(f_15_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_LessThan16Digits_WithTypeCharacter() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 16 significant digits precision, ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 13 significant digits Const f_13_1 As Double = .1499599999999R ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 Const f_13_2 As Double = 0.149959999999r ' Dev11 & Roslyn: Unchanged Const f_13_3 As Double = 1.499599999999# ' Dev11 & Roslyn: Unchanged Const f_13_4 As Double = 1499599.999999# ' Dev11 & Roslyn: Unchanged Const f_13_5 As Double = 149959999999.9r ' Dev11 & Roslyn: Unchanged Const f_13_6 As Double = 1499599999999.0R ' Dev11 & Roslyn: Unchanged ' 15 significant digits Const f_15_1 As Double = .149999999999995R ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 Const f_15_2 As Double = 0.14999999999995r ' Dev11 & Roslyn: Unchanged Const f_15_3 As Double = 1.49999999999995# ' Dev11 & Roslyn: Unchanged Const f_15_4 As Double = 14999999.9999995# ' Dev11 & Roslyn: Unchanged Const f_15_5 As Double = 14999999999999.5r ' Dev11 & Roslyn: Unchanged Const f_15_6 As Double = 149999999999995.0R ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_13_1) Console.WriteLine(f_13_2) Console.WriteLine(f_13_3) Console.WriteLine(f_13_4) Console.WriteLine(f_13_5) Console.WriteLine(f_13_6) Console.WriteLine(f_15_1) Console.WriteLine(f_15_2) Console.WriteLine(f_15_3) Console.WriteLine(f_15_4) Console.WriteLine(f_15_5) Console.WriteLine(f_15_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 16 significant digits precision, ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 13 significant digits Const f_13_1 As Double = 0.1499599999999R ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 Const f_13_2 As Double = 0.149959999999R ' Dev11 & Roslyn: Unchanged Const f_13_3 As Double = 1.499599999999# ' Dev11 & Roslyn: Unchanged Const f_13_4 As Double = 1499599.999999# ' Dev11 & Roslyn: Unchanged Const f_13_5 As Double = 149959999999.9R ' Dev11 & Roslyn: Unchanged Const f_13_6 As Double = 1499599999999.0R ' Dev11 & Roslyn: Unchanged ' 15 significant digits Const f_15_1 As Double = 0.149999999999995R ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 Const f_15_2 As Double = 0.14999999999995R ' Dev11 & Roslyn: Unchanged Const f_15_3 As Double = 1.49999999999995# ' Dev11 & Roslyn: Unchanged Const f_15_4 As Double = 14999999.9999995# ' Dev11 & Roslyn: Unchanged Const f_15_5 As Double = 14999999999999.5R ' Dev11 & Roslyn: Unchanged Const f_15_6 As Double = 149999999999995.0R ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_13_1) Console.WriteLine(f_13_2) Console.WriteLine(f_13_3) Console.WriteLine(f_13_4) Console.WriteLine(f_13_5) Console.WriteLine(f_13_6) Console.WriteLine(f_15_1) Console.WriteLine(f_15_2) Console.WriteLine(f_15_3) Console.WriteLine(f_15_4) Console.WriteLine(f_15_5) Console.WriteLine(f_15_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_16Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits Const f_16_1 As Double = .1499999999799993 ' Dev11 & Roslyn: 0.1499999999799993 Const f_16_2 As Double = .1499999999799997 ' Dev11 & Roslyn: 0.14999999997999969 Const f_16_3 As Double = 0.149999999799995 ' Dev11 & Roslyn: Unchanged Const f_16_4 As Double = 1.499999999799994 ' Dev11 & Roslyn: Unchanged Const f_16_5 As Double = 1.499999999799995 ' Dev11 & Roslyn: 1.4999999997999951 Const f_16_6 As Double = 14999999.99799994 ' Dev11 & Roslyn: Unchanged Const f_16_7 As Double = 14999999.99799995 ' Dev11 & Roslyn: 14999999.997999949 Const f_16_8 As Double = 149999999997999.2 ' Dev11 & Roslyn: 149999999997999.19 Const f_16_9 As Double = 149999999997999.8 ' Dev11 & Roslyn: 149999999997999.81 Const f_16_10 As Double = 1499999999979995.0 ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_16_1) Console.WriteLine(f_16_2) Console.WriteLine(f_16_3) Console.WriteLine(f_16_4) Console.WriteLine(f_16_5) Console.WriteLine(f_16_6) Console.WriteLine(f_16_7) Console.WriteLine(f_16_8) Console.WriteLine(f_16_9) Console.WriteLine(f_16_10) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 2: 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits Const f_16_1 As Double = 0.1499999999799993 ' Dev11 & Roslyn: 0.1499999999799993 Const f_16_2 As Double = {(IsNetCoreApp ? "0.1499999999799997" : "0.14999999997999969")} ' Dev11 & Roslyn: 0.14999999997999969 Const f_16_3 As Double = 0.149999999799995 ' Dev11 & Roslyn: Unchanged Const f_16_4 As Double = 1.499999999799994 ' Dev11 & Roslyn: Unchanged Const f_16_5 As Double = {(IsNetCoreApp ? "1.499999999799995" : "1.4999999997999951")} ' Dev11 & Roslyn: 1.4999999997999951 Const f_16_6 As Double = 14999999.99799994 ' Dev11 & Roslyn: Unchanged Const f_16_7 As Double = {(IsNetCoreApp ? "14999999.99799995" : "14999999.997999949")} ' Dev11 & Roslyn: 14999999.997999949 Const f_16_8 As Double = {(IsNetCoreApp ? "149999999997999.2" : "149999999997999.19")} ' Dev11 & Roslyn: 149999999997999.19 Const f_16_9 As Double = {(IsNetCoreApp ? "149999999997999.8" : "149999999997999.81")} ' Dev11 & Roslyn: 149999999997999.81 Const f_16_10 As Double = 1499999999979995.0 ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_16_1) Console.WriteLine(f_16_2) Console.WriteLine(f_16_3) Console.WriteLine(f_16_4) Console.WriteLine(f_16_5) Console.WriteLine(f_16_6) Console.WriteLine(f_16_7) Console.WriteLine(f_16_8) Console.WriteLine(f_16_9) Console.WriteLine(f_16_10) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_16Digits_WithTypeCharacter() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits Const f_16_1 As Double = .1499999999799993R ' Dev11 & Roslyn: 0.1499999999799993 Const f_16_2 As Double = .1499999999799997r ' Dev11 & Roslyn: 0.14999999997999969 Const f_16_3 As Double = 0.149999999799995# ' Dev11 & Roslyn: Unchanged Const f_16_4 As Double = 1.499999999799994R ' Dev11 & Roslyn: Unchanged Const f_16_5 As Double = 1.499999999799995r ' Dev11 & Roslyn: 1.4999999997999951 Const f_16_6 As Double = 14999999.99799994# ' Dev11 & Roslyn: Unchanged Const f_16_7 As Double = 14999999.99799995R ' Dev11 & Roslyn: 14999999.997999949 Const f_16_8 As Double = 149999999997999.2r ' Dev11 & Roslyn: 149999999997999.19 Const f_16_9 As Double = 149999999997999.8# ' Dev11 & Roslyn: 149999999997999.81 Const f_16_10 As Double = 1499999999979995.0R ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_16_1) Console.WriteLine(f_16_2) Console.WriteLine(f_16_3) Console.WriteLine(f_16_4) Console.WriteLine(f_16_5) Console.WriteLine(f_16_6) Console.WriteLine(f_16_7) Console.WriteLine(f_16_8) Console.WriteLine(f_16_9) Console.WriteLine(f_16_10) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 2: 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits Const f_16_1 As Double = 0.1499999999799993R ' Dev11 & Roslyn: 0.1499999999799993 Const f_16_2 As Double = {(IsNetCoreApp ? "0.1499999999799997R" : "0.14999999997999969R")} ' Dev11 & Roslyn: 0.14999999997999969 Const f_16_3 As Double = 0.149999999799995# ' Dev11 & Roslyn: Unchanged Const f_16_4 As Double = 1.499999999799994R ' Dev11 & Roslyn: Unchanged Const f_16_5 As Double = {(IsNetCoreApp ? "1.499999999799995R" : "1.4999999997999951R")} ' Dev11 & Roslyn: 1.4999999997999951 Const f_16_6 As Double = 14999999.99799994# ' Dev11 & Roslyn: Unchanged Const f_16_7 As Double = {(IsNetCoreApp ? "14999999.99799995R" : "14999999.997999949R")} ' Dev11 & Roslyn: 14999999.997999949 Const f_16_8 As Double = {(IsNetCoreApp ? "149999999997999.2R" : "149999999997999.19R")} ' Dev11 & Roslyn: 149999999997999.19 Const f_16_9 As Double = {(IsNetCoreApp ? "149999999997999.8#" : "149999999997999.81#")} ' Dev11 & Roslyn: 149999999997999.81 Const f_16_10 As Double = 1499999999979995.0R ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_16_1) Console.WriteLine(f_16_2) Console.WriteLine(f_16_3) Console.WriteLine(f_16_4) Console.WriteLine(f_16_5) Console.WriteLine(f_16_6) Console.WriteLine(f_16_7) Console.WriteLine(f_16_8) Console.WriteLine(f_16_9) Console.WriteLine(f_16_10) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_GreaterThan16Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 3: > 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits ' (a) > 16 significant digits overall, but < 16 digits before decimal point. Const f_17_1 As Double = .14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_2 As Double = .14999999997999939 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_3 As Double = .14999999997999937 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_4 As Double = 0.1499999997999957 ' Dev11 & Roslyn: Unchanged Const f_17_5 As Double = 0.1499999997999958 ' Dev11 & Roslyn: 0.14999999979999579 Const f_17_6 As Double = 1.4999999997999947 ' Dev11 & Roslyn: Unchanged Const f_17_7 As Double = 1.4999999997999945 ' Dev11 & Roslyn: 1.4999999997999944 Const f_17_8 As Double = 1.4999999997999946 ' Dev11 & Roslyn: 1.4999999997999947 Const f_18_1 As Double = 14999999.9979999459 ' Dev11 & Roslyn: 14999999.997999946 Const f_18_2 As Double = 14999999.9979999451 ' Dev11 & Roslyn: 14999999.997999946 Const f_18_3 As Double = 14999999.9979999454 ' Dev11 & Roslyn: 14999999.997999946 ' (b) > 16 significant digits before decimal point. Const f_18_4 As Double = 14999999999733999.2 ' Dev11 & Roslyn: 1.4999999999734E+16 Const f_18_5 As Double = 14999999999379995.0 ' Dev11 & Roslyn: 14999999999379996.0 Const f_24_1 As Double = 111111149999124689999.499 ' Dev11 & Roslyn: 1.1111114999912469E+20 ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. Const f_overflow_1 As Double = -1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Double = 1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Double = -4.94065645841246544E-326 ' Dev11: -0.0F, Roslyn: unchanged Const f_underflow_2 As Double = 4.94065645841246544E-326 ' Dev11: 0.0F, Roslyn: unchanged Console.WriteLine(f_17_1) Console.WriteLine(f_17_2) Console.WriteLine(f_17_3) Console.WriteLine(f_17_4) Console.WriteLine(f_17_5) Console.WriteLine(f_17_6) Console.WriteLine(f_17_7) Console.WriteLine(f_17_8) Console.WriteLine(f_18_1) Console.WriteLine(f_18_2) Console.WriteLine(f_18_3) Console.WriteLine(f_18_4) Console.WriteLine(f_18_5) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 3: > 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits ' (a) > 16 significant digits overall, but < 16 digits before decimal point. Const f_17_1 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_2 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_3 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_4 As Double = 0.1499999997999957 ' Dev11 & Roslyn: Unchanged Const f_17_5 As Double = {(IsNetCoreApp ? "0.1499999997999958" : "0.14999999979999579")} ' Dev11 & Roslyn: 0.14999999979999579 Const f_17_6 As Double = 1.4999999997999947 ' Dev11 & Roslyn: Unchanged Const f_17_7 As Double = 1.4999999997999944 ' Dev11 & Roslyn: 1.4999999997999944 Const f_17_8 As Double = 1.4999999997999947 ' Dev11 & Roslyn: 1.4999999997999947 Const f_18_1 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 Const f_18_2 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 Const f_18_3 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 ' (b) > 16 significant digits before decimal point. Const f_18_4 As Double = {(IsNetCoreApp ? "14999999999734000.0" : "1.4999999999734E+16")} ' Dev11 & Roslyn: 1.4999999999734E+16 Const f_18_5 As Double = 14999999999379996.0 ' Dev11 & Roslyn: 14999999999379996.0 Const f_24_1 As Double = {(IsNetCoreApp ? "1.111111499991247E+20" : "1.1111114999912469E+20")} ' Dev11 & Roslyn: 1.1111114999912469E+20 ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. Const f_overflow_1 As Double = -1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Double = 1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Double = -4.94065645841246544E-326 ' Dev11: -0.0F, Roslyn: unchanged Const f_underflow_2 As Double = 4.94065645841246544E-326 ' Dev11: 0.0F, Roslyn: unchanged Console.WriteLine(f_17_1) Console.WriteLine(f_17_2) Console.WriteLine(f_17_3) Console.WriteLine(f_17_4) Console.WriteLine(f_17_5) Console.WriteLine(f_17_6) Console.WriteLine(f_17_7) Console.WriteLine(f_17_8) Console.WriteLine(f_18_1) Console.WriteLine(f_18_2) Console.WriteLine(f_18_3) Console.WriteLine(f_18_4) Console.WriteLine(f_18_5) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_GreaterThan16Digits_WithTypeCharacter() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 3: > 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits ' (a) > 16 significant digits overall, but < 16 digits before decimal point. Const f_17_1 As Double = .14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_2 As Double = .14999999997999939r ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_3 As Double = .14999999997999937# ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_4 As Double = 0.1499999997999957R ' Dev11 & Roslyn: Unchanged Const f_17_5 As Double = 0.1499999997999958r ' Dev11 & Roslyn: 0.14999999979999579 Const f_17_6 As Double = 1.4999999997999947# ' Dev11 & Roslyn: Unchanged Const f_17_7 As Double = 1.4999999997999945R ' Dev11 & Roslyn: 1.4999999997999944 Const f_17_8 As Double = 1.4999999997999946r ' Dev11 & Roslyn: 1.4999999997999947 Const f_18_1 As Double = 14999999.9979999459# ' Dev11 & Roslyn: 14999999.997999946 Const f_18_2 As Double = 14999999.9979999451R ' Dev11 & Roslyn: 14999999.997999946 Const f_18_3 As Double = 14999999.9979999454r ' Dev11 & Roslyn: 14999999.997999946 ' (b) > 16 significant digits before decimal point. Const f_18_4 As Double = 14999999999733999.2# ' Dev11 & Roslyn: 1.4999999999734E+16 Const f_18_5 As Double = 14999999999379995.0R ' Dev11 & Roslyn: 14999999999379996.0 Const f_24_1 As Double = 111111149999124689999.499r ' Dev11 & Roslyn: 1.1111114999912469E+20 ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. Const f_overflow_1 As Double = -1.79769313486231570E+309# ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Double = 1.79769313486231570E+309R ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Double = -4.94065645841246544E-326r ' Dev11: -0.0F, Roslyn: unchanged Const f_underflow_2 As Double = 4.94065645841246544E-326# ' Dev11: 0.0F, Roslyn: unchanged Console.WriteLine(f_17_1) Console.WriteLine(f_17_2) Console.WriteLine(f_17_3) Console.WriteLine(f_17_4) Console.WriteLine(f_17_5) Console.WriteLine(f_17_6) Console.WriteLine(f_17_7) Console.WriteLine(f_17_8) Console.WriteLine(f_18_1) Console.WriteLine(f_18_2) Console.WriteLine(f_18_3) Console.WriteLine(f_18_4) Console.WriteLine(f_18_5) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 3: > 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits ' (a) > 16 significant digits overall, but < 16 digits before decimal point. Const f_17_1 As Double = 0.14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_2 As Double = 0.14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_3 As Double = 0.14999999997999938# ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_4 As Double = 0.1499999997999957R ' Dev11 & Roslyn: Unchanged Const f_17_5 As Double = {(IsNetCoreApp ? "0.1499999997999958R" : "0.14999999979999579R")} ' Dev11 & Roslyn: 0.14999999979999579 Const f_17_6 As Double = 1.4999999997999947# ' Dev11 & Roslyn: Unchanged Const f_17_7 As Double = 1.4999999997999944R ' Dev11 & Roslyn: 1.4999999997999944 Const f_17_8 As Double = 1.4999999997999947R ' Dev11 & Roslyn: 1.4999999997999947 Const f_18_1 As Double = 14999999.997999946# ' Dev11 & Roslyn: 14999999.997999946 Const f_18_2 As Double = 14999999.997999946R ' Dev11 & Roslyn: 14999999.997999946 Const f_18_3 As Double = 14999999.997999946R ' Dev11 & Roslyn: 14999999.997999946 ' (b) > 16 significant digits before decimal point. Const f_18_4 As Double = {(IsNetCoreApp ? "14999999999734000.0#" : "1.4999999999734E+16#")} ' Dev11 & Roslyn: 1.4999999999734E+16 Const f_18_5 As Double = 14999999999379996.0R ' Dev11 & Roslyn: 14999999999379996.0 Const f_24_1 As Double = {(IsNetCoreApp ? "1.111111499991247E+20R" : "1.1111114999912469E+20R")} ' Dev11 & Roslyn: 1.1111114999912469E+20 ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. Const f_overflow_1 As Double = -1.79769313486231570E+309# ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Double = 1.79769313486231570E+309R ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Double = -4.94065645841246544E-326R ' Dev11: -0.0F, Roslyn: unchanged Const f_underflow_2 As Double = 4.94065645841246544E-326# ' Dev11: 0.0F, Roslyn: unchanged Console.WriteLine(f_17_1) Console.WriteLine(f_17_2) Console.WriteLine(f_17_3) Console.WriteLine(f_17_4) Console.WriteLine(f_17_5) Console.WriteLine(f_17_6) Console.WriteLine(f_17_7) Console.WriteLine(f_17_8) Console.WriteLine(f_18_1) Console.WriteLine(f_18_2) Console.WriteLine(f_18_3) Console.WriteLine(f_18_4) Console.WriteLine(f_18_5) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiterals_LessThan30Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 30 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 27 significant digits Const d_27_1 As Decimal = .123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D Const d_27_2 As Decimal = 0.123456789012345678901234567d ' Dev11 & Roslyn: Unchanged Const d_27_3 As Decimal = 1.23456789012345678901234567D ' Dev11 & Roslyn: Unchanged Const d_27_4 As Decimal = 123456789012.345678901234567d ' Dev11 & Roslyn: Unchanged Const d_27_5 As Decimal = 12345678901234567890123456.7D ' Dev11 & Roslyn: Unchanged Const d_27_6 As Decimal = 123456789012345678901234567.0d ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D ' 29 significant digits Const d_29_1 As Decimal = .12345678901234567890123456789D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_29_2 As Decimal = 0.12345678901234567890123456789d ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_29_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: Unchanged Const d_29_4 As Decimal = 123456789012.34567890123456789d ' Dev11 & Roslyn: Unchanged Const d_29_5 As Decimal = 1234567890123456789012345678.9D ' Dev11 & Roslyn: Unchanged Const d_29_6 As Decimal = 12345678901234567890123456789.0d ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D Console.WriteLine(d_27_1) Console.WriteLine(d_27_2) Console.WriteLine(d_27_3) Console.WriteLine(d_27_4) Console.WriteLine(d_27_5) Console.WriteLine(d_27_6) Console.WriteLine(d_29_1) Console.WriteLine(d_29_2) Console.WriteLine(d_29_3) Console.WriteLine(d_29_4) Console.WriteLine(d_29_5) Console.WriteLine(d_29_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 30 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 27 significant digits Const d_27_1 As Decimal = 0.123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D Const d_27_2 As Decimal = 0.123456789012345678901234567D ' Dev11 & Roslyn: Unchanged Const d_27_3 As Decimal = 1.23456789012345678901234567D ' Dev11 & Roslyn: Unchanged Const d_27_4 As Decimal = 123456789012.345678901234567D ' Dev11 & Roslyn: Unchanged Const d_27_5 As Decimal = 12345678901234567890123456.7D ' Dev11 & Roslyn: Unchanged Const d_27_6 As Decimal = 123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D ' 29 significant digits Const d_29_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_29_2 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_29_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: Unchanged Const d_29_4 As Decimal = 123456789012.34567890123456789D ' Dev11 & Roslyn: Unchanged Const d_29_5 As Decimal = 1234567890123456789012345678.9D ' Dev11 & Roslyn: Unchanged Const d_29_6 As Decimal = 12345678901234567890123456789D ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D Console.WriteLine(d_27_1) Console.WriteLine(d_27_2) Console.WriteLine(d_27_3) Console.WriteLine(d_27_4) Console.WriteLine(d_27_5) Console.WriteLine(d_27_6) Console.WriteLine(d_29_1) Console.WriteLine(d_29_2) Console.WriteLine(d_29_3) Console.WriteLine(d_29_4) Console.WriteLine(d_29_5) Console.WriteLine(d_29_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiterals_LessThan30Digits_WithTypeCharacterDecimal() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 30 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 27 significant digits Const d_27_1 As Decimal = .123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D Const d_27_2 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_3 As Decimal = 1.23456789012345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_4 As Decimal = 123456789012.345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_5 As Decimal = 12345678901234567890123456.7@ ' Dev11 & Roslyn: Unchanged Const d_27_6 As Decimal = 123456789012345678901234567.0@ ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D ' 29 significant digits Const d_29_1 As Decimal = .12345678901234567890123456789@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ Const d_29_2 As Decimal = 0.12345678901234567890123456789@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ Const d_29_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: Unchanged Const d_29_4 As Decimal = 123456789012.34567890123456789@ ' Dev11 & Roslyn: Unchanged Const d_29_5 As Decimal = 1234567890123456789012345678.9@ ' Dev11 & Roslyn: Unchanged Const d_29_6 As Decimal = 12345678901234567890123456789.0@ ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D Console.WriteLine(d_27_1) Console.WriteLine(d_27_2) Console.WriteLine(d_27_3) Console.WriteLine(d_27_4) Console.WriteLine(d_27_5) Console.WriteLine(d_27_6) Console.WriteLine(d_29_1) Console.WriteLine(d_29_2) Console.WriteLine(d_29_3) Console.WriteLine(d_29_4) Console.WriteLine(d_29_5) Console.WriteLine(d_29_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 30 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 27 significant digits Const d_27_1 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D Const d_27_2 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_3 As Decimal = 1.23456789012345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_4 As Decimal = 123456789012.345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_5 As Decimal = 12345678901234567890123456.7@ ' Dev11 & Roslyn: Unchanged Const d_27_6 As Decimal = 123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D ' 29 significant digits Const d_29_1 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ Const d_29_2 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ Const d_29_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: Unchanged Const d_29_4 As Decimal = 123456789012.34567890123456789@ ' Dev11 & Roslyn: Unchanged Const d_29_5 As Decimal = 1234567890123456789012345678.9@ ' Dev11 & Roslyn: Unchanged Const d_29_6 As Decimal = 12345678901234567890123456789@ ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D Console.WriteLine(d_27_1) Console.WriteLine(d_27_2) Console.WriteLine(d_27_3) Console.WriteLine(d_27_4) Console.WriteLine(d_27_5) Console.WriteLine(d_27_6) Console.WriteLine(d_29_1) Console.WriteLine(d_29_2) Console.WriteLine(d_29_3) Console.WriteLine(d_29_4) Console.WriteLine(d_29_5) Console.WriteLine(d_29_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiterals_30Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 30 significant digits ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits Const d_30_1 As Decimal = .123456789012345678901234567891D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_30_2 As Decimal = 0.1234567890123456789012345687891D ' Dev11 & Roslyn: 0.1234567890123456789012345688D Const d_30_3 As Decimal = 1.23456789012345678901234567891D ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_30_4 As Decimal = 123456789012345.678901234567891D ' Dev11 & Roslyn: 123456789012345.67890123456789D Const d_30_5 As Decimal = 12345678901234567890123456789.1D ' Dev11 & Roslyn: 12345678901234567890123456789D ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. Const d_30_6 As Decimal = 123456789012345678901234567891.0D ' Dev11 & Roslyn: 123456789012345678901234567891.0D Console.WriteLine(d_30_1) Console.WriteLine(d_30_2) Console.WriteLine(d_30_3) Console.WriteLine(d_30_4) Console.WriteLine(d_30_5) Console.WriteLine(d_30_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 2: 30 significant digits ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits Const d_30_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_30_2 As Decimal = 0.1234567890123456789012345688D ' Dev11 & Roslyn: 0.1234567890123456789012345688D Const d_30_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_30_4 As Decimal = 123456789012345.67890123456789D ' Dev11 & Roslyn: 123456789012345.67890123456789D Const d_30_5 As Decimal = 12345678901234567890123456789D ' Dev11 & Roslyn: 12345678901234567890123456789D ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. Const d_30_6 As Decimal = 123456789012345678901234567891.0D ' Dev11 & Roslyn: 123456789012345678901234567891.0D Console.WriteLine(d_30_1) Console.WriteLine(d_30_2) Console.WriteLine(d_30_3) Console.WriteLine(d_30_4) Console.WriteLine(d_30_5) Console.WriteLine(d_30_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiterals_30Digits_WithTypeCharacterDecimal() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 30 significant digits ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits Const d_30_1 As Decimal = .123456789012345678901234567891@ ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_30_2 As Decimal = 0.1234567890123456789012345687891@ ' Dev11 & Roslyn: 0.1234567890123456789012345688D Const d_30_3 As Decimal = 1.23456789012345678901234567891@ ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_30_4 As Decimal = 123456789012345.678901234567891@ ' Dev11 & Roslyn: 123456789012345.67890123456789D Const d_30_5 As Decimal = 12345678901234567890123456789.1@ ' Dev11 & Roslyn: 12345678901234567890123456789D ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. Const d_30_6 As Decimal = 123456789012345678901234567891.0@ ' Dev11 & Roslyn: 123456789012345678901234567891.0D Console.WriteLine(d_30_1) Console.WriteLine(d_30_2) Console.WriteLine(d_30_3) Console.WriteLine(d_30_4) Console.WriteLine(d_30_5) Console.WriteLine(d_30_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 2: 30 significant digits ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits Const d_30_1 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_30_2 As Decimal = 0.1234567890123456789012345688@ ' Dev11 & Roslyn: 0.1234567890123456789012345688D Const d_30_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_30_4 As Decimal = 123456789012345.67890123456789@ ' Dev11 & Roslyn: 123456789012345.67890123456789D Const d_30_5 As Decimal = 12345678901234567890123456789@ ' Dev11 & Roslyn: 12345678901234567890123456789D ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. Const d_30_6 As Decimal = 123456789012345678901234567891.0@ ' Dev11 & Roslyn: 123456789012345678901234567891.0D Console.WriteLine(d_30_1) Console.WriteLine(d_30_2) Console.WriteLine(d_30_3) Console.WriteLine(d_30_4) Console.WriteLine(d_30_5) Console.WriteLine(d_30_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiterals_GreaterThan30Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 3: > 30 significant digits ' Dev11 has unpredictable behavior: pretty listed/round off to wrong values in certain cases ' Roslyn behavior: Always rounded off + pretty listed to <= 29 significant digits ' (a) > 30 significant digits overall, but < 30 digits before decimal point. Const d_32_1 As Decimal = .12345678901234567890123456789012D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_32_2 As Decimal = 0.123456789012345678901234568789012@ ' Dev11 & Roslyn: 0.1234567890123456789012345688@ Const d_32_3 As Decimal = 1.2345678901234567890123456789012d ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_32_4 As Decimal = 123456789012345.67890123456789012@ ' Dev11 & Roslyn: 123456789012345.67890123456789@ ' (b) > 30 significant digits before decimal point (Overflow case): Ensure no pretty listing. Const d_35_1 As Decimal = 123456789012345678901234567890123.45D ' Dev11 & Roslyn: 123456789012345678901234567890123.45D Console.WriteLine(d_32_1) Console.WriteLine(d_32_2) Console.WriteLine(d_32_3) Console.WriteLine(d_32_4) Console.WriteLine(d_35_1) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 3: > 30 significant digits ' Dev11 has unpredictable behavior: pretty listed/round off to wrong values in certain cases ' Roslyn behavior: Always rounded off + pretty listed to <= 29 significant digits ' (a) > 30 significant digits overall, but < 30 digits before decimal point. Const d_32_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_32_2 As Decimal = 0.1234567890123456789012345688@ ' Dev11 & Roslyn: 0.1234567890123456789012345688@ Const d_32_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_32_4 As Decimal = 123456789012345.67890123456789@ ' Dev11 & Roslyn: 123456789012345.67890123456789@ ' (b) > 30 significant digits before decimal point (Overflow case): Ensure no pretty listing. Const d_35_1 As Decimal = 123456789012345678901234567890123.45D ' Dev11 & Roslyn: 123456789012345678901234567890123.45D Console.WriteLine(d_32_1) Console.WriteLine(d_32_2) Console.WriteLine(d_32_3) Console.WriteLine(d_32_4) Console.WriteLine(d_35_1) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceFloatLiteralsWithNegativeExponents() { var code = @"[| Module Program Sub Main(args As String()) ' Floating point values might be represented either in fixed point notation or scientific/exponent notation. ' MSDN comment for Standard Numeric Format Strings used in Single.ToString(String) API (or Double.ToString(String)): ' Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and ' less than the precision specifier; otherwise, scientific notation is used. ' ' However, Dev11 pretty lister differs from this for floating point values < 0. It uses fixed point notation as long as exponent is greater than '-(actualPrecision + 1)'. ' For example, consider Single Floating literals: ' (i) Precision = 7 ' 0.0000001234567F => 0.0000001234567F (exponent = -7: fixed point notation) ' 0.00000001234567F => 0.00000001234567F (exponent = -8: fixed point notation) ' 0.000000001234567F => 1.234567E-9F (exponent = -9: exponent notation) ' 0.0000000001234567F => 1.234567E-10F (exponent = -10: exponent notation) ' (ii) Precision = 9 ' 0.0000000012345678F => 0.00000000123456778F (exponent = -9: fixed point notation) ' 0.00000000012345678F => 0.000000000123456786F (exponent = -10: fixed point notation) ' 0.000000000012345678F => 1.23456783E-11F (exponent = -11: exponent notation) ' 0.0000000000012345678F => 1.23456779E-12F (exponent = -12: exponent notation) Const f_1 As Single = 0.000001234567F Const f_2 As Single = 0.0000001234567F Const f_3 As Single = 0.00000001234567F Const f_4 As Single = 0.000000001234567F ' Change at -9 Const f_5 As Single = 0.0000000001234567F Const f_6 As Single = 0.00000000123456778F Const f_7 As Single = 0.000000000123456786F Const f_8 As Single = 0.000000000012345678F ' Change at -11 Const f_9 As Single = 0.0000000000012345678F Const d_1 As Single = 0.00000000000000123456789012345 Const d_2 As Single = 0.000000000000000123456789012345 Const d_3 As Single = 0.0000000000000000123456789012345 ' Change at -17 Const d_4 As Single = 0.00000000000000000123456789012345 Const d_5 As Double = 0.00000000000000001234567890123456 Const d_6 As Double = 0.000000000000000001234567890123456 Const d_7 As Double = 0.0000000000000000001234567890123456 ' Change at -19 Const d_8 As Double = 0.00000000000000000001234567890123456 End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' Floating point values might be represented either in fixed point notation or scientific/exponent notation. ' MSDN comment for Standard Numeric Format Strings used in Single.ToString(String) API (or Double.ToString(String)): ' Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and ' less than the precision specifier; otherwise, scientific notation is used. ' ' However, Dev11 pretty lister differs from this for floating point values < 0. It uses fixed point notation as long as exponent is greater than '-(actualPrecision + 1)'. ' For example, consider Single Floating literals: ' (i) Precision = 7 ' 0.0000001234567F => 0.0000001234567F (exponent = -7: fixed point notation) ' 0.00000001234567F => 0.00000001234567F (exponent = -8: fixed point notation) ' 0.000000001234567F => 1.234567E-9F (exponent = -9: exponent notation) ' 0.0000000001234567F => 1.234567E-10F (exponent = -10: exponent notation) ' (ii) Precision = 9 ' 0.0000000012345678F => 0.00000000123456778F (exponent = -9: fixed point notation) ' 0.00000000012345678F => 0.000000000123456786F (exponent = -10: fixed point notation) ' 0.000000000012345678F => 1.23456783E-11F (exponent = -11: exponent notation) ' 0.0000000000012345678F => 1.23456779E-12F (exponent = -12: exponent notation) Const f_1 As Single = 0.000001234567F Const f_2 As Single = 0.0000001234567F Const f_3 As Single = 0.00000001234567F Const f_4 As Single = 1.234567E-9F ' Change at -9 Const f_5 As Single = 1.234567E-10F Const f_6 As Single = {(IsNetCoreApp ? "0.0000000012345678F" : "0.00000000123456778F")} Const f_7 As Single = {(IsNetCoreApp ? "0.00000000012345679F" : "0.000000000123456786F")} Const f_8 As Single = {(IsNetCoreApp ? "1.2345678E-11F" : "1.23456783E-11F")} ' Change at -11 Const f_9 As Single = {(IsNetCoreApp ? "1.2345678E-12F" : "1.23456779E-12F")} Const d_1 As Single = 0.00000000000000123456789012345 Const d_2 As Single = 0.000000000000000123456789012345 Const d_3 As Single = 1.23456789012345E-17 ' Change at -17 Const d_4 As Single = 1.23456789012345E-18 Const d_5 As Double = {(IsNetCoreApp ? "0.00000000000000001234567890123456" : "0.000000000000000012345678901234561")} Const d_6 As Double = 0.000000000000000001234567890123456 Const d_7 As Double = {(IsNetCoreApp ? "1.234567890123456E-19" : "1.2345678901234561E-19")} ' Change at -19 Const d_8 As Double = 1.234567890123456E-20 End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiteralsWithTrailingZeros() { var code = @"[| Module Program Sub Main(args As String()) Const f1 As Single = 3.011000F ' Dev11 & Roslyn: 3.011F Const f2 As Single = 3.000000! ' Dev11 & Roslyn: 3.0! Const f3 As Single = 3.0F ' Dev11 & Roslyn: Unchanged Const f4 As Single = 3000f ' Dev11 & Roslyn: 3000.0F Const f5 As Single = 3000E+10! ' Dev11 & Roslyn: 3.0E+13! Const f6 As Single = 3000.0E+10F ' Dev11 & Roslyn: 3.0E+13F Const f7 As Single = 3000.010E+1F ' Dev11 & Roslyn: 30000.1F Const f8 As Single = 3000.123456789010E+10! ' Dev11 & Roslyn: 3.00012337E+13! Const f9 As Single = 3000.123456789000E+10F ' Dev11 & Roslyn: 3.00012337E+13F Const f10 As Single = 30001234567890.10E-10f ' Dev11 & Roslyn: 3000.12354F Const f11 As Single = 3000E-10! ' Dev11 & Roslyn: 0.0000003! Console.WriteLine(f1) Console.WriteLine(f2) Console.WriteLine(f3) Console.WriteLine(f4) Console.WriteLine(f5) Console.WriteLine(f6) Console.WriteLine(f7) Console.WriteLine(f8) Console.WriteLine(f9) Console.WriteLine(f10) Console.WriteLine(f11) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) Const f1 As Single = 3.011F ' Dev11 & Roslyn: 3.011F Const f2 As Single = 3.0! ' Dev11 & Roslyn: 3.0! Const f3 As Single = 3.0F ' Dev11 & Roslyn: Unchanged Const f4 As Single = 3000.0F ' Dev11 & Roslyn: 3000.0F Const f5 As Single = 3.0E+13! ' Dev11 & Roslyn: 3.0E+13! Const f6 As Single = 3.0E+13F ' Dev11 & Roslyn: 3.0E+13F Const f7 As Single = 30000.1F ' Dev11 & Roslyn: 30000.1F Const f8 As Single = {(IsNetCoreApp ? "3.0001234E+13!" : "3.00012337E+13!")} ' Dev11 & Roslyn: 3.00012337E+13! Const f9 As Single = {(IsNetCoreApp ? "3.0001234E+13F" : "3.00012337E+13F")} ' Dev11 & Roslyn: 3.00012337E+13F Const f10 As Single = {(IsNetCoreApp ? "3000.1235F" : "3000.12354F")} ' Dev11 & Roslyn: 3000.12354F Const f11 As Single = 0.0000003! ' Dev11 & Roslyn: 0.0000003! Console.WriteLine(f1) Console.WriteLine(f2) Console.WriteLine(f3) Console.WriteLine(f4) Console.WriteLine(f5) Console.WriteLine(f6) Console.WriteLine(f7) Console.WriteLine(f8) Console.WriteLine(f9) Console.WriteLine(f10) Console.WriteLine(f11) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiteralsWithTrailingZeros() { var code = @"[| Module Program Sub Main(args As String()) Const d1 As Double = 3.011000 ' Dev11 & Roslyn: 3.011 Const d2 As Double = 3.000000 ' Dev11 & Roslyn: 3.0 Const d3 As Double = 3.0 ' Dev11 & Roslyn: Unchanged Const d4 As Double = 3000R ' Dev11 & Roslyn: 3000.0R Const d5 As Double = 3000E+10# ' Dev11 & Roslyn: 30000000000000.0# Const d6 As Double = 3000.0E+10 ' Dev11 & Roslyn: 30000000000000.0 Const d7 As Double = 3000.010E+1 ' Dev11 & Roslyn: 30000.1 Const d8 As Double = 3000.123456789010E+10# ' Dev11 & Roslyn: 30001234567890.1# Const d9 As Double = 3000.123456789000E+10 ' Dev11 & Roslyn: 30001234567890.0 Const d10 As Double = 30001234567890.10E-10d ' Dev11 & Roslyn: 3000.12345678901D Const d11 As Double = 3000E-10 ' Dev11 & Roslyn: 0.0000003 Console.WriteLine(d1) Console.WriteLine(d2) Console.WriteLine(d3) Console.WriteLine(d4) Console.WriteLine(d5) Console.WriteLine(d6) Console.WriteLine(d7) Console.WriteLine(d8) Console.WriteLine(d9) Console.WriteLine(d10) Console.WriteLine(d11) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) Const d1 As Double = 3.011 ' Dev11 & Roslyn: 3.011 Const d2 As Double = 3.0 ' Dev11 & Roslyn: 3.0 Const d3 As Double = 3.0 ' Dev11 & Roslyn: Unchanged Const d4 As Double = 3000.0R ' Dev11 & Roslyn: 3000.0R Const d5 As Double = 30000000000000.0# ' Dev11 & Roslyn: 30000000000000.0# Const d6 As Double = 30000000000000.0 ' Dev11 & Roslyn: 30000000000000.0 Const d7 As Double = 30000.1 ' Dev11 & Roslyn: 30000.1 Const d8 As Double = 30001234567890.1# ' Dev11 & Roslyn: 30001234567890.1# Const d9 As Double = 30001234567890.0 ' Dev11 & Roslyn: 30001234567890.0 Const d10 As Double = 3000.12345678901D ' Dev11 & Roslyn: 3000.12345678901D Const d11 As Double = 0.0000003 ' Dev11 & Roslyn: 0.0000003 Console.WriteLine(d1) Console.WriteLine(d2) Console.WriteLine(d3) Console.WriteLine(d4) Console.WriteLine(d5) Console.WriteLine(d6) Console.WriteLine(d7) Console.WriteLine(d8) Console.WriteLine(d9) Console.WriteLine(d10) Console.WriteLine(d11) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiteralsWithTrailingZeros() { var code = @"[| Module Program Sub Main(args As String()) Const d1 As Decimal = 3.011000D ' Dev11 & Roslyn: 3.011D Const d2 As Decimal = 3.000000D ' Dev11 & Roslyn: 3D Const d3 As Decimal = 3.0D ' Dev11 & Roslyn: 3D Const d4 As Decimal = 3000D ' Dev11 & Roslyn: 3000D Const d5 As Decimal = 3000E+10D ' Dev11 & Roslyn: 30000000000000D Const d6 As Decimal = 3000.0E+10D ' Dev11 & Roslyn: 30000000000000D Const d7 As Decimal = 3000.010E+1D ' Dev11 & Roslyn: 30000.1D Const d8 As Decimal = 3000.123456789010E+10D ' Dev11 & Roslyn: 30001234567890.1D Const d9 As Decimal = 3000.123456789000E+10D ' Dev11 & Roslyn: 30001234567890D Const d10 As Decimal = 30001234567890.10E-10D ' Dev11 & Roslyn: 3000.12345678901D Const d11 As Decimal = 3000E-10D ' Dev11 & Roslyn: 0.0000003D Console.WriteLine(d1) Console.WriteLine(d2) Console.WriteLine(d3) Console.WriteLine(d4) Console.WriteLine(d5) Console.WriteLine(d6) Console.WriteLine(d7) Console.WriteLine(d8) Console.WriteLine(d9) Console.WriteLine(d10) Console.WriteLine(d11) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) Const d1 As Decimal = 3.011D ' Dev11 & Roslyn: 3.011D Const d2 As Decimal = 3D ' Dev11 & Roslyn: 3D Const d3 As Decimal = 3D ' Dev11 & Roslyn: 3D Const d4 As Decimal = 3000D ' Dev11 & Roslyn: 3000D Const d5 As Decimal = 30000000000000D ' Dev11 & Roslyn: 30000000000000D Const d6 As Decimal = 30000000000000D ' Dev11 & Roslyn: 30000000000000D Const d7 As Decimal = 30000.1D ' Dev11 & Roslyn: 30000.1D Const d8 As Decimal = 30001234567890.1D ' Dev11 & Roslyn: 30001234567890.1D Const d9 As Decimal = 30001234567890D ' Dev11 & Roslyn: 30001234567890D Const d10 As Decimal = 3000.12345678901D ' Dev11 & Roslyn: 3000.12345678901D Const d11 As Decimal = 0.0000003D ' Dev11 & Roslyn: 0.0000003D Console.WriteLine(d1) Console.WriteLine(d2) Console.WriteLine(d3) Console.WriteLine(d4) Console.WriteLine(d5) Console.WriteLine(d6) Console.WriteLine(d7) Console.WriteLine(d8) Console.WriteLine(d9) Console.WriteLine(d10) Console.WriteLine(d11) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(623319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623319")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceFloatingAndDecimalLiteralsWithDifferentCulture() { var savedCulture = System.Threading.Thread.CurrentThread.CurrentCulture; try { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"); var code = @"[| Module Program Sub Main(args As String()) Dim d = 1.0D Dim f = 1.0F Dim x = 1.0 End Sub End Module|]"; var expected = @" Module Program Sub Main(args As String()) Dim d = 1D Dim f = 1.0F Dim x = 1.0 End Sub End Module"; await VerifyAsync(code, expected); } finally { System.Threading.Thread.CurrentThread.CurrentCulture = savedCulture; } } [Fact] [WorkItem(652147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/652147")] public async Task ReduceFloatingAndDecimalLiteralsWithInvariantCultureNegatives() { var oldCulture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = (CultureInfo)oldCulture.Clone(); Thread.CurrentThread.CurrentCulture.NumberFormat.NegativeSign = "~"; var code = @"[| Module Program Sub Main(args As String()) Dim d = -1.0E-11D Dim f = -1.0E-11F Dim x = -1.0E-11 End Sub End Module|]"; var expected = @" Module Program Sub Main(args As String()) Dim d = -0.00000000001D Dim f = -1.0E-11F Dim x = -0.00000000001 End Sub End Module"; await VerifyAsync(code, expected); } finally { Thread.CurrentThread.CurrentCulture = oldCulture; } } [Fact] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceIntegerLiteralWithLeadingZeros() { var code = @"[| Module Program Sub Main(args As String()) Const i0 As Integer = 0060 Const i1 As Integer = 0060% Const i2 As Integer = &H006F Const i3 As Integer = &O0060 Const i4 As Integer = 0060I Const i5 As Integer = -0060 Const i6 As Integer = 000 Const i7 As UInteger = 0060UI Const i8 As Integer = &H0000FFFFI Const i9 As Integer = &O000 Const i10 As Integer = &H000 Const l0 As Long = 0060L Const l1 As Long = 0060& Const l2 As ULong = 0060UL Const s0 As Short = 0060S Const s1 As UShort = 0060US Const s2 As Short = &H0000FFFFS End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) Const i0 As Integer = 60 Const i1 As Integer = 60% Const i2 As Integer = &H6F Const i3 As Integer = &O60 Const i4 As Integer = 60I Const i5 As Integer = -60 Const i6 As Integer = 0 Const i7 As UInteger = 60UI Const i8 As Integer = &HFFFFI Const i9 As Integer = &O0 Const i10 As Integer = &H0 Const l0 As Long = 60L Const l1 As Long = 60& Const l2 As ULong = 60UL Const s0 As Short = 60S Const s1 As UShort = 60US Const s2 As Short = &HFFFFS End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceIntegerLiteralWithNegativeHexOrOctalValue() { var code = @"[| Module Program Sub Main(args As String()) Const s0 As Short = &HFFFFS Const s1 As Short = &O177777S Const s2 As Short = &H8000S Const s3 As Short = &O100000S Const i0 As Integer = &O37777777777I Const i1 As Integer = &HFFFFFFFFI Const i2 As Integer = &H80000000I Const i3 As Integer = &O20000000000I Const l0 As Long = &HFFFFFFFFFFFFFFFFL Const l1 As Long = &O1777777777777777777777L Const l2 As Long = &H8000000000000000L Const l2 As Long = &O1000000000000000000000L End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) Const s0 As Short = &HFFFFS Const s1 As Short = &O177777S Const s2 As Short = &H8000S Const s3 As Short = &O100000S Const i0 As Integer = &O37777777777I Const i1 As Integer = &HFFFFFFFFI Const i2 As Integer = &H80000000I Const i3 As Integer = &O20000000000I Const l0 As Long = &HFFFFFFFFFFFFFFFFL Const l1 As Long = &O1777777777777777777777L Const l2 As Long = &H8000000000000000L Const l2 As Long = &O1000000000000000000000L End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceIntegerLiteralWithOverflow() { var code = @"[| Module Module1 Sub Main() Dim sMax As Short = 0032768S Dim usMax As UShort = 00655536US Dim iMax As Integer = 002147483648I Dim uiMax As UInteger = 004294967296UI Dim lMax As Long = 009223372036854775808L Dim ulMax As ULong = 0018446744073709551616UL Dim z As Long = &O37777777777777777777777 Dim x As Long = &HFFFFFFFFFFFFFFFFF End Sub End Module |]"; var expected = @" Module Module1 Sub Main() Dim sMax As Short = 0032768S Dim usMax As UShort = 00655536US Dim iMax As Integer = 002147483648I Dim uiMax As UInteger = 004294967296UI Dim lMax As Long = 009223372036854775808L Dim ulMax As ULong = 0018446744073709551616UL Dim z As Long = &O37777777777777777777777 Dim x As Long = &HFFFFFFFFFFFFFFFFF End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceBinaryIntegerLiteral() { var code = @"[| Module Module1 Sub Main() ' signed Dim a As SByte = &B0111 Dim b As Short = &B0101 Dim c As Integer = &B00100100 Dim d As Long = &B001001100110 ' unsigned Dim e As Byte = &B01011 Dim f As UShort = &B00100 Dim g As UInteger = &B001001100110 Dim h As ULong = &B001001100110 ' negative Dim i As SByte = -&B0111 Dim j As Short = -&B00101 Dim k As Integer = -&B00100100 Dim l As Long = -&B001001100110 ' negative literal Dim m As SByte = &B10000001 Dim n As Short = &B1000000000000001 Dim o As Integer = &B10000000000000000000000000000001 Dim p As Long = &B1000000000000000000000000000000000000000000000000000000000000001 End Sub End Module |]"; var expected = @" Module Module1 Sub Main() ' signed Dim a As SByte = &B111 Dim b As Short = &B101 Dim c As Integer = &B100100 Dim d As Long = &B1001100110 ' unsigned Dim e As Byte = &B1011 Dim f As UShort = &B100 Dim g As UInteger = &B1001100110 Dim h As ULong = &B1001100110 ' negative Dim i As SByte = -&B111 Dim j As Short = -&B101 Dim k As Integer = -&B100100 Dim l As Long = -&B1001100110 ' negative literal Dim m As SByte = &B10000001 Dim n As Short = &B1000000000000001 Dim o As Integer = &B10000000000000000000000000000001 Dim p As Long = &B1000000000000000000000000000000000000000000000000000000000000001 End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(14034, "https://github.com/dotnet/roslyn/issues/14034")] [WorkItem(48492, "https://github.com/dotnet/roslyn/issues/48492")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task DoNotReduceDigitSeparators() { var source = @" Module Module1 Sub Main() Dim x = 100_000 Dim y = 100_000.0F Dim z = 100_000.0D End Sub End Module "; var expected = source; await VerifyAsync($"[|{source}|]", expected); } private static async Task VerifyAsync(string codeWithMarker, string expectedResult) { MarkupTestFile.GetSpans(codeWithMarker, out var codeWithoutMarker, out ImmutableArray<TextSpan> textSpans); var document = CreateDocument(codeWithoutMarker, LanguageNames.VisualBasic); var codeCleanups = CodeCleaner.GetDefaultProviders(document).WhereAsArray(p => p.Name == PredefinedCodeCleanupProviderNames.ReduceTokens || p.Name == PredefinedCodeCleanupProviderNames.CaseCorrection || p.Name == PredefinedCodeCleanupProviderNames.Format); var cleanDocument = await CodeCleaner.CleanupAsync(document, textSpans[0], codeCleanups); AssertEx.EqualOrDiff(expectedResult, (await cleanDocument.GetSyntaxRootAsync()).ToFullString()); } private static Document CreateDocument(string code, string language) { var solution = new AdhocWorkspace().CurrentSolution; var projectId = ProjectId.CreateNewId(); var project = solution.AddProject(projectId, "Project", "Project.dll", language).GetProject(projectId); return project.AddMetadataReference(TestMetadata.Net451.mscorlib) .AddDocument("Document", SourceText.From(code)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeCleanup.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup { [UseExportProvider] public class ReduceTokenTests { #if NETCOREAPP private static bool IsNetCoreApp => true; #else private static bool IsNetCoreApp => false; #endif [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_LessThan8Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 8 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 5 significant digits Const f_5_1 As Single = .14995F ' Dev11 & Roslyn: Pretty listed to 0.14995F Const f_5_2 As Single = 0.14995f ' Dev11 & Roslyn: Unchanged Const f_5_3 As Single = 1.4995F ' Dev11 & Roslyn: Unchanged Const f_5_4 As Single = 149.95f ' Dev11 & Roslyn: Unchanged Const f_5_5 As Single = 1499.5F ' Dev11 & Roslyn: Unchanged Const f_5_6 As Single = 14995.0f ' Dev11 & Roslyn: Unchanged ' 7 significant digits Const f_7_1 As Single = .1499995F ' Dev11 & Roslyn: Pretty listed to 0.1499995F Const f_7_2 As Single = 0.1499995f ' Dev11 & Roslyn: Unchanged Const f_7_3 As Single = 1.499995F ' Dev11 & Roslyn: Unchanged Const f_7_4 As Single = 1499.995f ' Dev11 & Roslyn: Unchanged Const f_7_5 As Single = 149999.5F ' Dev11 & Roslyn: Unchanged Const f_7_6 As Single = 1499995.0f ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_5_1) Console.WriteLine(f_5_2) Console.WriteLine(f_5_3) Console.WriteLine(f_5_4) Console.WriteLine(f_5_5) Console.WriteLine(f_5_6) Console.WriteLine(f_7_1) Console.WriteLine(f_7_2) Console.WriteLine(f_7_3) Console.WriteLine(f_7_4) Console.WriteLine(f_7_5) Console.WriteLine(f_7_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 8 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 5 significant digits Const f_5_1 As Single = 0.14995F ' Dev11 & Roslyn: Pretty listed to 0.14995F Const f_5_2 As Single = 0.14995F ' Dev11 & Roslyn: Unchanged Const f_5_3 As Single = 1.4995F ' Dev11 & Roslyn: Unchanged Const f_5_4 As Single = 149.95F ' Dev11 & Roslyn: Unchanged Const f_5_5 As Single = 1499.5F ' Dev11 & Roslyn: Unchanged Const f_5_6 As Single = 14995.0F ' Dev11 & Roslyn: Unchanged ' 7 significant digits Const f_7_1 As Single = 0.1499995F ' Dev11 & Roslyn: Pretty listed to 0.1499995F Const f_7_2 As Single = 0.1499995F ' Dev11 & Roslyn: Unchanged Const f_7_3 As Single = 1.499995F ' Dev11 & Roslyn: Unchanged Const f_7_4 As Single = 1499.995F ' Dev11 & Roslyn: Unchanged Const f_7_5 As Single = 149999.5F ' Dev11 & Roslyn: Unchanged Const f_7_6 As Single = 1499995.0F ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_5_1) Console.WriteLine(f_5_2) Console.WriteLine(f_5_3) Console.WriteLine(f_5_4) Console.WriteLine(f_5_5) Console.WriteLine(f_5_6) Console.WriteLine(f_7_1) Console.WriteLine(f_7_2) Console.WriteLine(f_7_3) Console.WriteLine(f_7_4) Console.WriteLine(f_7_5) Console.WriteLine(f_7_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_LessThan8Digits_WithTypeCharacterSingle() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 8 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 5 significant digits Const f_5_1 As Single = .14995! ' Dev11 & Roslyn: Pretty listed to 0.14995! Const f_5_2 As Single = 0.14995! ' Dev11 & Roslyn: Unchanged Const f_5_3 As Single = 1.4995! ' Dev11 & Roslyn: Unchanged Const f_5_4 As Single = 149.95! ' Dev11 & Roslyn: Unchanged Const f_5_5 As Single = 1499.5! ' Dev11 & Roslyn: Unchanged Const f_5_6 As Single = 14995.0! ' Dev11 & Roslyn: Unchanged ' 7 significant digits Const f_7_1 As Single = .1499995! ' Dev11 & Roslyn: Pretty listed to 0.1499995! Const f_7_2 As Single = 0.1499995! ' Dev11 & Roslyn: Unchanged Const f_7_3 As Single = 1.499995! ' Dev11 & Roslyn: Unchanged Const f_7_4 As Single = 1499.995! ' Dev11 & Roslyn: Unchanged Const f_7_5 As Single = 149999.5! ' Dev11 & Roslyn: Unchanged Const f_7_6 As Single = 1499995.0! ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_5_1) Console.WriteLine(f_5_2) Console.WriteLine(f_5_3) Console.WriteLine(f_5_4) Console.WriteLine(f_5_5) Console.WriteLine(f_5_6) Console.WriteLine(f_7_1) Console.WriteLine(f_7_2) Console.WriteLine(f_7_3) Console.WriteLine(f_7_4) Console.WriteLine(f_7_5) Console.WriteLine(f_7_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 8 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 5 significant digits Const f_5_1 As Single = 0.14995! ' Dev11 & Roslyn: Pretty listed to 0.14995! Const f_5_2 As Single = 0.14995! ' Dev11 & Roslyn: Unchanged Const f_5_3 As Single = 1.4995! ' Dev11 & Roslyn: Unchanged Const f_5_4 As Single = 149.95! ' Dev11 & Roslyn: Unchanged Const f_5_5 As Single = 1499.5! ' Dev11 & Roslyn: Unchanged Const f_5_6 As Single = 14995.0! ' Dev11 & Roslyn: Unchanged ' 7 significant digits Const f_7_1 As Single = 0.1499995! ' Dev11 & Roslyn: Pretty listed to 0.1499995! Const f_7_2 As Single = 0.1499995! ' Dev11 & Roslyn: Unchanged Const f_7_3 As Single = 1.499995! ' Dev11 & Roslyn: Unchanged Const f_7_4 As Single = 1499.995! ' Dev11 & Roslyn: Unchanged Const f_7_5 As Single = 149999.5! ' Dev11 & Roslyn: Unchanged Const f_7_6 As Single = 1499995.0! ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_5_1) Console.WriteLine(f_5_2) Console.WriteLine(f_5_3) Console.WriteLine(f_5_4) Console.WriteLine(f_5_5) Console.WriteLine(f_5_6) Console.WriteLine(f_7_1) Console.WriteLine(f_7_2) Console.WriteLine(f_7_3) Console.WriteLine(f_7_4) Console.WriteLine(f_7_5) Console.WriteLine(f_7_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_8Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits Const f_8_1 As Single = .14999795F ' Dev11 & Roslyn: 0.14999795F Const f_8_2 As Single = .14999797f ' Dev11 & Roslyn: 0.149997965F Const f_8_3 As Single = 0.1499797F ' Dev11 & Roslyn: Unchanged Const f_8_4 As Single = 1.4999794f ' Dev11 & Roslyn: 1.49997938F Const f_8_5 As Single = 1.4999797F ' Dev11 & Roslyn: 1.49997973F Const f_8_6 As Single = 1499.9794f ' Dev11 & Roslyn: 1499.97937F Const f_8_7 As Single = 1499979.7F ' Dev11 & Roslyn: 1499979.75F Const f_8_8 As Single = 14999797.0F ' Dev11 & Roslyn: unchanged Console.WriteLine(f_8_1) Console.WriteLine(f_8_2) Console.WriteLine(f_8_3) Console.WriteLine(f_8_4) Console.WriteLine(f_8_5) Console.WriteLine(f_8_6) Console.WriteLine(f_8_7) Console.WriteLine(f_8_8) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 2: 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits Const f_8_1 As Single = 0.14999795F ' Dev11 & Roslyn: 0.14999795F Const f_8_2 As Single = {(IsNetCoreApp ? "0.14999796F" : "0.149997965F")} ' Dev11 & Roslyn: 0.149997965F Const f_8_3 As Single = 0.1499797F ' Dev11 & Roslyn: Unchanged Const f_8_4 As Single = {(IsNetCoreApp ? "1.4999794F" : "1.49997938F")} ' Dev11 & Roslyn: 1.49997938F Const f_8_5 As Single = {(IsNetCoreApp ? "1.4999797F" : "1.49997973F")} ' Dev11 & Roslyn: 1.49997973F Const f_8_6 As Single = {(IsNetCoreApp ? "1499.9794F" : "1499.97937F")} ' Dev11 & Roslyn: 1499.97937F Const f_8_7 As Single = {(IsNetCoreApp ? "1499979.8F" : "1499979.75F")} ' Dev11 & Roslyn: 1499979.75F Const f_8_8 As Single = 14999797.0F ' Dev11 & Roslyn: unchanged Console.WriteLine(f_8_1) Console.WriteLine(f_8_2) Console.WriteLine(f_8_3) Console.WriteLine(f_8_4) Console.WriteLine(f_8_5) Console.WriteLine(f_8_6) Console.WriteLine(f_8_7) Console.WriteLine(f_8_8) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_8Digits_WithTypeCharacterSingle() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits Const f_8_1 As Single = .14999795! ' Dev11 & Roslyn: 0.14999795F Const f_8_2 As Single = .14999797! ' Dev11 & Roslyn: 0.149997965F Const f_8_3 As Single = 0.1499797! ' Dev11 & Roslyn: Unchanged Const f_8_4 As Single = 1.4999794! ' Dev11 & Roslyn: 1.49997938F Const f_8_5 As Single = 1.4999797! ' Dev11 & Roslyn: 1.49997973F Const f_8_6 As Single = 1499.9794! ' Dev11 & Roslyn: 1499.97937F Const f_8_7 As Single = 1499979.7! ' Dev11 & Roslyn: 1499979.75F Const f_8_8 As Single = 14999797.0! ' Dev11 & Roslyn: unchanged Console.WriteLine(f_8_1) Console.WriteLine(f_8_2) Console.WriteLine(f_8_3) Console.WriteLine(f_8_4) Console.WriteLine(f_8_5) Console.WriteLine(f_8_6) Console.WriteLine(f_8_7) Console.WriteLine(f_8_8) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 2: 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits Const f_8_1 As Single = 0.14999795! ' Dev11 & Roslyn: 0.14999795F Const f_8_2 As Single = {(IsNetCoreApp ? "0.14999796!" : "0.149997965!")} ' Dev11 & Roslyn: 0.149997965F Const f_8_3 As Single = 0.1499797! ' Dev11 & Roslyn: Unchanged Const f_8_4 As Single = {(IsNetCoreApp ? "1.4999794!" : "1.49997938!")} ' Dev11 & Roslyn: 1.49997938F Const f_8_5 As Single = {(IsNetCoreApp ? "1.4999797!" : "1.49997973!")} ' Dev11 & Roslyn: 1.49997973F Const f_8_6 As Single = {(IsNetCoreApp ? "1499.9794!" : "1499.97937!")} ' Dev11 & Roslyn: 1499.97937F Const f_8_7 As Single = {(IsNetCoreApp ? "1499979.8!" : "1499979.75!")} ' Dev11 & Roslyn: 1499979.75F Const f_8_8 As Single = 14999797.0! ' Dev11 & Roslyn: unchanged Console.WriteLine(f_8_1) Console.WriteLine(f_8_2) Console.WriteLine(f_8_3) Console.WriteLine(f_8_4) Console.WriteLine(f_8_5) Console.WriteLine(f_8_6) Console.WriteLine(f_8_7) Console.WriteLine(f_8_8) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_GreaterThan8Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 3: > 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits ' (a) > 8 significant digits overall, but < 8 digits before decimal point. Const f_9_1 As Single = .149997938F ' Dev11 & Roslyn: 0.149997935F Const f_9_2 As Single = 0.149997931f ' Dev11 & Roslyn: 0.149997935F Const f_9_3 As Single = 1.49997965F ' Dev11 & Roslyn: 1.49997962F Const f_10_1 As Single = 14999.79652f ' Dev11 & Roslyn: 14999.7969F ' (b) > 8 significant digits before decimal point. Const f_10_2 As Single = 149997965.2F ' Dev11 & Roslyn: 149997968.0F Const f_10_3 As Single = 1499979652.0f ' Dev11 & Roslyn: 1.49997965E+9F Const f_24_1 As Single = 111111149999124689999.499F ' Dev11 & Roslyn: 1.11111148E+20F ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and ' from 1.401298E-45 through 3.4028235E+38 for positive values. Const f_overflow_1 As Single = -3.4028235E+39F ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Single = 3.4028235E+39F ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Single = -1.401298E-47F ' Dev11: -0.0F, Roslyn: Unchanged Const f_underflow_2 As Single = 1.401298E-47F ' Dev11: 0.0F, Roslyn: Unchanged Console.WriteLine(f_9_1) Console.WriteLine(f_9_2) Console.WriteLine(f_9_3) Console.WriteLine(f_10_1) Console.WriteLine(f_10_2) Console.WriteLine(f_10_3) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 3: > 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits ' (a) > 8 significant digits overall, but < 8 digits before decimal point. Const f_9_1 As Single = {(IsNetCoreApp ? "0.14999793F" : "0.149997935F")} ' Dev11 & Roslyn: 0.149997935F Const f_9_2 As Single = {(IsNetCoreApp ? "0.14999793F" : "0.149997935F")} ' Dev11 & Roslyn: 0.149997935F Const f_9_3 As Single = {(IsNetCoreApp ? "1.4999796F" : "1.49997962F")} ' Dev11 & Roslyn: 1.49997962F Const f_10_1 As Single = {(IsNetCoreApp ? "14999.797F" : "14999.7969F")} ' Dev11 & Roslyn: 14999.7969F ' (b) > 8 significant digits before decimal point. Const f_10_2 As Single = {(IsNetCoreApp ? "149997970.0F" : "149997968.0F")} ' Dev11 & Roslyn: 149997968.0F Const f_10_3 As Single = {(IsNetCoreApp ? "1.4999796E+9F" : "1.49997965E+9F")} ' Dev11 & Roslyn: 1.49997965E+9F Const f_24_1 As Single = {(IsNetCoreApp ? "1.1111115E+20F" : "1.11111148E+20F")} ' Dev11 & Roslyn: 1.11111148E+20F ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and ' from 1.401298E-45 through 3.4028235E+38 for positive values. Const f_overflow_1 As Single = -3.4028235E+39F ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Single = 3.4028235E+39F ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Single = -1.401298E-47F ' Dev11: -0.0F, Roslyn: Unchanged Const f_underflow_2 As Single = 1.401298E-47F ' Dev11: 0.0F, Roslyn: Unchanged Console.WriteLine(f_9_1) Console.WriteLine(f_9_2) Console.WriteLine(f_9_3) Console.WriteLine(f_10_1) Console.WriteLine(f_10_2) Console.WriteLine(f_10_3) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiterals_GreaterThan8Digits_WithTypeCharacterSingle() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 3: > 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits ' (a) > 8 significant digits overall, but < 8 digits before decimal point. Const f_9_1 As Single = .149997938! ' Dev11 & Roslyn: 0.149997935F Const f_9_2 As Single = 0.149997931! ' Dev11 & Roslyn: 0.149997935F Const f_9_3 As Single = 1.49997965! ' Dev11 & Roslyn: 1.49997962F Const f_10_1 As Single = 14999.79652! ' Dev11 & Roslyn: 14999.7969F ' (b) > 8 significant digits before decimal point. Const f_10_2 As Single = 149997965.2! ' Dev11 & Roslyn: 149997968.0F Const f_10_3 As Single = 1499979652.0! ' Dev11 & Roslyn: 1.49997965E+9F Const f_24_1 As Single = 111111149999124689999.499! ' Dev11 & Roslyn: 1.11111148E+20F ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and ' from 1.401298E-45 through 3.4028235E+38 for positive values. Const f_overflow_1 As Single = -3.4028235E+39! ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Single = 3.4028235E+39! ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Single = -1.401298E-47! ' Dev11: -0.0F, Roslyn: Unchanged Const f_underflow_2 As Single = 1.401298E-47! ' Dev11: 0.0F, Roslyn: Unchanged Console.WriteLine(f_9_1) Console.WriteLine(f_9_2) Console.WriteLine(f_9_3) Console.WriteLine(f_10_1) Console.WriteLine(f_10_2) Console.WriteLine(f_10_3) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 3: > 8 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 9 significant digits ' (a) > 8 significant digits overall, but < 8 digits before decimal point. Const f_9_1 As Single = {(IsNetCoreApp ? "0.14999793!" : "0.149997935!")} ' Dev11 & Roslyn: 0.149997935F Const f_9_2 As Single = {(IsNetCoreApp ? "0.14999793!" : "0.149997935!")} ' Dev11 & Roslyn: 0.149997935F Const f_9_3 As Single = {(IsNetCoreApp ? "1.4999796!" : "1.49997962!")} ' Dev11 & Roslyn: 1.49997962F Const f_10_1 As Single = {(IsNetCoreApp ? "14999.797!" : "14999.7969!")} ' Dev11 & Roslyn: 14999.7969F ' (b) > 8 significant digits before decimal point. Const f_10_2 As Single = {(IsNetCoreApp ? "149997970.0!" : "149997968.0!")} ' Dev11 & Roslyn: 149997968.0F Const f_10_3 As Single = {(IsNetCoreApp ? "1.4999796E+9!" : "1.49997965E+9!")} ' Dev11 & Roslyn: 1.49997965E+9F Const f_24_1 As Single = {(IsNetCoreApp ? "1.1111115E+20!" : "1.11111148E+20!")} ' Dev11 & Roslyn: 1.11111148E+20F ' (c) Overflow/Underflow cases for Single: Ensure no pretty listing/round off ' Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -1.401298E-45 for negative values and ' from 1.401298E-45 through 3.4028235E+38 for positive values. Const f_overflow_1 As Single = -3.4028235E+39! ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Single = 3.4028235E+39! ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Single = -1.401298E-47! ' Dev11: -0.0F, Roslyn: Unchanged Const f_underflow_2 As Single = 1.401298E-47! ' Dev11: 0.0F, Roslyn: Unchanged Console.WriteLine(f_9_1) Console.WriteLine(f_9_2) Console.WriteLine(f_9_3) Console.WriteLine(f_10_1) Console.WriteLine(f_10_2) Console.WriteLine(f_10_3) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_LessThan16Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 16 significant digits precision, ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 13 significant digits Const f_13_1 As Double = .1499599999999 ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 Const f_13_2 As Double = 0.149959999999 ' Dev11 & Roslyn: Unchanged Const f_13_3 As Double = 1.499599999999 ' Dev11 & Roslyn: Unchanged Const f_13_4 As Double = 1499599.999999 ' Dev11 & Roslyn: Unchanged Const f_13_5 As Double = 149959999999.9 ' Dev11 & Roslyn: Unchanged Const f_13_6 As Double = 1499599999999.0 ' Dev11 & Roslyn: Unchanged ' 15 significant digits Const f_15_1 As Double = .149999999999995 ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 Const f_15_2 As Double = 0.14999999999995 ' Dev11 & Roslyn: Unchanged Const f_15_3 As Double = 1.49999999999995 ' Dev11 & Roslyn: Unchanged Const f_15_4 As Double = 14999999.9999995 ' Dev11 & Roslyn: Unchanged Const f_15_5 As Double = 14999999999999.5 ' Dev11 & Roslyn: Unchanged Const f_15_6 As Double = 149999999999995.0 ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_13_1) Console.WriteLine(f_13_2) Console.WriteLine(f_13_3) Console.WriteLine(f_13_4) Console.WriteLine(f_13_5) Console.WriteLine(f_13_6) Console.WriteLine(f_15_1) Console.WriteLine(f_15_2) Console.WriteLine(f_15_3) Console.WriteLine(f_15_4) Console.WriteLine(f_15_5) Console.WriteLine(f_15_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 16 significant digits precision, ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 13 significant digits Const f_13_1 As Double = 0.1499599999999 ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 Const f_13_2 As Double = 0.149959999999 ' Dev11 & Roslyn: Unchanged Const f_13_3 As Double = 1.499599999999 ' Dev11 & Roslyn: Unchanged Const f_13_4 As Double = 1499599.999999 ' Dev11 & Roslyn: Unchanged Const f_13_5 As Double = 149959999999.9 ' Dev11 & Roslyn: Unchanged Const f_13_6 As Double = 1499599999999.0 ' Dev11 & Roslyn: Unchanged ' 15 significant digits Const f_15_1 As Double = 0.149999999999995 ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 Const f_15_2 As Double = 0.14999999999995 ' Dev11 & Roslyn: Unchanged Const f_15_3 As Double = 1.49999999999995 ' Dev11 & Roslyn: Unchanged Const f_15_4 As Double = 14999999.9999995 ' Dev11 & Roslyn: Unchanged Const f_15_5 As Double = 14999999999999.5 ' Dev11 & Roslyn: Unchanged Const f_15_6 As Double = 149999999999995.0 ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_13_1) Console.WriteLine(f_13_2) Console.WriteLine(f_13_3) Console.WriteLine(f_13_4) Console.WriteLine(f_13_5) Console.WriteLine(f_13_6) Console.WriteLine(f_15_1) Console.WriteLine(f_15_2) Console.WriteLine(f_15_3) Console.WriteLine(f_15_4) Console.WriteLine(f_15_5) Console.WriteLine(f_15_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_LessThan16Digits_WithTypeCharacter() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 16 significant digits precision, ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 13 significant digits Const f_13_1 As Double = .1499599999999R ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 Const f_13_2 As Double = 0.149959999999r ' Dev11 & Roslyn: Unchanged Const f_13_3 As Double = 1.499599999999# ' Dev11 & Roslyn: Unchanged Const f_13_4 As Double = 1499599.999999# ' Dev11 & Roslyn: Unchanged Const f_13_5 As Double = 149959999999.9r ' Dev11 & Roslyn: Unchanged Const f_13_6 As Double = 1499599999999.0R ' Dev11 & Roslyn: Unchanged ' 15 significant digits Const f_15_1 As Double = .149999999999995R ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 Const f_15_2 As Double = 0.14999999999995r ' Dev11 & Roslyn: Unchanged Const f_15_3 As Double = 1.49999999999995# ' Dev11 & Roslyn: Unchanged Const f_15_4 As Double = 14999999.9999995# ' Dev11 & Roslyn: Unchanged Const f_15_5 As Double = 14999999999999.5r ' Dev11 & Roslyn: Unchanged Const f_15_6 As Double = 149999999999995.0R ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_13_1) Console.WriteLine(f_13_2) Console.WriteLine(f_13_3) Console.WriteLine(f_13_4) Console.WriteLine(f_13_5) Console.WriteLine(f_13_6) Console.WriteLine(f_15_1) Console.WriteLine(f_15_2) Console.WriteLine(f_15_3) Console.WriteLine(f_15_4) Console.WriteLine(f_15_5) Console.WriteLine(f_15_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 16 significant digits precision, ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 13 significant digits Const f_13_1 As Double = 0.1499599999999R ' Dev11 & Roslyn: Pretty listed to 0.1499599999999 Const f_13_2 As Double = 0.149959999999R ' Dev11 & Roslyn: Unchanged Const f_13_3 As Double = 1.499599999999# ' Dev11 & Roslyn: Unchanged Const f_13_4 As Double = 1499599.999999# ' Dev11 & Roslyn: Unchanged Const f_13_5 As Double = 149959999999.9R ' Dev11 & Roslyn: Unchanged Const f_13_6 As Double = 1499599999999.0R ' Dev11 & Roslyn: Unchanged ' 15 significant digits Const f_15_1 As Double = 0.149999999999995R ' Dev11 & Roslyn: Pretty listed to 0.149999999999995 Const f_15_2 As Double = 0.14999999999995R ' Dev11 & Roslyn: Unchanged Const f_15_3 As Double = 1.49999999999995# ' Dev11 & Roslyn: Unchanged Const f_15_4 As Double = 14999999.9999995# ' Dev11 & Roslyn: Unchanged Const f_15_5 As Double = 14999999999999.5R ' Dev11 & Roslyn: Unchanged Const f_15_6 As Double = 149999999999995.0R ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_13_1) Console.WriteLine(f_13_2) Console.WriteLine(f_13_3) Console.WriteLine(f_13_4) Console.WriteLine(f_13_5) Console.WriteLine(f_13_6) Console.WriteLine(f_15_1) Console.WriteLine(f_15_2) Console.WriteLine(f_15_3) Console.WriteLine(f_15_4) Console.WriteLine(f_15_5) Console.WriteLine(f_15_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_16Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits Const f_16_1 As Double = .1499999999799993 ' Dev11 & Roslyn: 0.1499999999799993 Const f_16_2 As Double = .1499999999799997 ' Dev11 & Roslyn: 0.14999999997999969 Const f_16_3 As Double = 0.149999999799995 ' Dev11 & Roslyn: Unchanged Const f_16_4 As Double = 1.499999999799994 ' Dev11 & Roslyn: Unchanged Const f_16_5 As Double = 1.499999999799995 ' Dev11 & Roslyn: 1.4999999997999951 Const f_16_6 As Double = 14999999.99799994 ' Dev11 & Roslyn: Unchanged Const f_16_7 As Double = 14999999.99799995 ' Dev11 & Roslyn: 14999999.997999949 Const f_16_8 As Double = 149999999997999.2 ' Dev11 & Roslyn: 149999999997999.19 Const f_16_9 As Double = 149999999997999.8 ' Dev11 & Roslyn: 149999999997999.81 Const f_16_10 As Double = 1499999999979995.0 ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_16_1) Console.WriteLine(f_16_2) Console.WriteLine(f_16_3) Console.WriteLine(f_16_4) Console.WriteLine(f_16_5) Console.WriteLine(f_16_6) Console.WriteLine(f_16_7) Console.WriteLine(f_16_8) Console.WriteLine(f_16_9) Console.WriteLine(f_16_10) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 2: 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits Const f_16_1 As Double = 0.1499999999799993 ' Dev11 & Roslyn: 0.1499999999799993 Const f_16_2 As Double = {(IsNetCoreApp ? "0.1499999999799997" : "0.14999999997999969")} ' Dev11 & Roslyn: 0.14999999997999969 Const f_16_3 As Double = 0.149999999799995 ' Dev11 & Roslyn: Unchanged Const f_16_4 As Double = 1.499999999799994 ' Dev11 & Roslyn: Unchanged Const f_16_5 As Double = {(IsNetCoreApp ? "1.499999999799995" : "1.4999999997999951")} ' Dev11 & Roslyn: 1.4999999997999951 Const f_16_6 As Double = 14999999.99799994 ' Dev11 & Roslyn: Unchanged Const f_16_7 As Double = {(IsNetCoreApp ? "14999999.99799995" : "14999999.997999949")} ' Dev11 & Roslyn: 14999999.997999949 Const f_16_8 As Double = {(IsNetCoreApp ? "149999999997999.2" : "149999999997999.19")} ' Dev11 & Roslyn: 149999999997999.19 Const f_16_9 As Double = {(IsNetCoreApp ? "149999999997999.8" : "149999999997999.81")} ' Dev11 & Roslyn: 149999999997999.81 Const f_16_10 As Double = 1499999999979995.0 ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_16_1) Console.WriteLine(f_16_2) Console.WriteLine(f_16_3) Console.WriteLine(f_16_4) Console.WriteLine(f_16_5) Console.WriteLine(f_16_6) Console.WriteLine(f_16_7) Console.WriteLine(f_16_8) Console.WriteLine(f_16_9) Console.WriteLine(f_16_10) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_16Digits_WithTypeCharacter() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits Const f_16_1 As Double = .1499999999799993R ' Dev11 & Roslyn: 0.1499999999799993 Const f_16_2 As Double = .1499999999799997r ' Dev11 & Roslyn: 0.14999999997999969 Const f_16_3 As Double = 0.149999999799995# ' Dev11 & Roslyn: Unchanged Const f_16_4 As Double = 1.499999999799994R ' Dev11 & Roslyn: Unchanged Const f_16_5 As Double = 1.499999999799995r ' Dev11 & Roslyn: 1.4999999997999951 Const f_16_6 As Double = 14999999.99799994# ' Dev11 & Roslyn: Unchanged Const f_16_7 As Double = 14999999.99799995R ' Dev11 & Roslyn: 14999999.997999949 Const f_16_8 As Double = 149999999997999.2r ' Dev11 & Roslyn: 149999999997999.19 Const f_16_9 As Double = 149999999997999.8# ' Dev11 & Roslyn: 149999999997999.81 Const f_16_10 As Double = 1499999999979995.0R ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_16_1) Console.WriteLine(f_16_2) Console.WriteLine(f_16_3) Console.WriteLine(f_16_4) Console.WriteLine(f_16_5) Console.WriteLine(f_16_6) Console.WriteLine(f_16_7) Console.WriteLine(f_16_8) Console.WriteLine(f_16_9) Console.WriteLine(f_16_10) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 2: 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits Const f_16_1 As Double = 0.1499999999799993R ' Dev11 & Roslyn: 0.1499999999799993 Const f_16_2 As Double = {(IsNetCoreApp ? "0.1499999999799997R" : "0.14999999997999969R")} ' Dev11 & Roslyn: 0.14999999997999969 Const f_16_3 As Double = 0.149999999799995# ' Dev11 & Roslyn: Unchanged Const f_16_4 As Double = 1.499999999799994R ' Dev11 & Roslyn: Unchanged Const f_16_5 As Double = {(IsNetCoreApp ? "1.499999999799995R" : "1.4999999997999951R")} ' Dev11 & Roslyn: 1.4999999997999951 Const f_16_6 As Double = 14999999.99799994# ' Dev11 & Roslyn: Unchanged Const f_16_7 As Double = {(IsNetCoreApp ? "14999999.99799995R" : "14999999.997999949R")} ' Dev11 & Roslyn: 14999999.997999949 Const f_16_8 As Double = {(IsNetCoreApp ? "149999999997999.2R" : "149999999997999.19R")} ' Dev11 & Roslyn: 149999999997999.19 Const f_16_9 As Double = {(IsNetCoreApp ? "149999999997999.8#" : "149999999997999.81#")} ' Dev11 & Roslyn: 149999999997999.81 Const f_16_10 As Double = 1499999999979995.0R ' Dev11 & Roslyn: Unchanged Console.WriteLine(f_16_1) Console.WriteLine(f_16_2) Console.WriteLine(f_16_3) Console.WriteLine(f_16_4) Console.WriteLine(f_16_5) Console.WriteLine(f_16_6) Console.WriteLine(f_16_7) Console.WriteLine(f_16_8) Console.WriteLine(f_16_9) Console.WriteLine(f_16_10) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_GreaterThan16Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 3: > 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits ' (a) > 16 significant digits overall, but < 16 digits before decimal point. Const f_17_1 As Double = .14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_2 As Double = .14999999997999939 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_3 As Double = .14999999997999937 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_4 As Double = 0.1499999997999957 ' Dev11 & Roslyn: Unchanged Const f_17_5 As Double = 0.1499999997999958 ' Dev11 & Roslyn: 0.14999999979999579 Const f_17_6 As Double = 1.4999999997999947 ' Dev11 & Roslyn: Unchanged Const f_17_7 As Double = 1.4999999997999945 ' Dev11 & Roslyn: 1.4999999997999944 Const f_17_8 As Double = 1.4999999997999946 ' Dev11 & Roslyn: 1.4999999997999947 Const f_18_1 As Double = 14999999.9979999459 ' Dev11 & Roslyn: 14999999.997999946 Const f_18_2 As Double = 14999999.9979999451 ' Dev11 & Roslyn: 14999999.997999946 Const f_18_3 As Double = 14999999.9979999454 ' Dev11 & Roslyn: 14999999.997999946 ' (b) > 16 significant digits before decimal point. Const f_18_4 As Double = 14999999999733999.2 ' Dev11 & Roslyn: 1.4999999999734E+16 Const f_18_5 As Double = 14999999999379995.0 ' Dev11 & Roslyn: 14999999999379996.0 Const f_24_1 As Double = 111111149999124689999.499 ' Dev11 & Roslyn: 1.1111114999912469E+20 ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. Const f_overflow_1 As Double = -1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Double = 1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Double = -4.94065645841246544E-326 ' Dev11: -0.0F, Roslyn: unchanged Const f_underflow_2 As Double = 4.94065645841246544E-326 ' Dev11: 0.0F, Roslyn: unchanged Console.WriteLine(f_17_1) Console.WriteLine(f_17_2) Console.WriteLine(f_17_3) Console.WriteLine(f_17_4) Console.WriteLine(f_17_5) Console.WriteLine(f_17_6) Console.WriteLine(f_17_7) Console.WriteLine(f_17_8) Console.WriteLine(f_18_1) Console.WriteLine(f_18_2) Console.WriteLine(f_18_3) Console.WriteLine(f_18_4) Console.WriteLine(f_18_5) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 3: > 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits ' (a) > 16 significant digits overall, but < 16 digits before decimal point. Const f_17_1 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_2 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_3 As Double = 0.14999999997999938 ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_4 As Double = 0.1499999997999957 ' Dev11 & Roslyn: Unchanged Const f_17_5 As Double = {(IsNetCoreApp ? "0.1499999997999958" : "0.14999999979999579")} ' Dev11 & Roslyn: 0.14999999979999579 Const f_17_6 As Double = 1.4999999997999947 ' Dev11 & Roslyn: Unchanged Const f_17_7 As Double = 1.4999999997999944 ' Dev11 & Roslyn: 1.4999999997999944 Const f_17_8 As Double = 1.4999999997999947 ' Dev11 & Roslyn: 1.4999999997999947 Const f_18_1 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 Const f_18_2 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 Const f_18_3 As Double = 14999999.997999946 ' Dev11 & Roslyn: 14999999.997999946 ' (b) > 16 significant digits before decimal point. Const f_18_4 As Double = {(IsNetCoreApp ? "14999999999734000.0" : "1.4999999999734E+16")} ' Dev11 & Roslyn: 1.4999999999734E+16 Const f_18_5 As Double = 14999999999379996.0 ' Dev11 & Roslyn: 14999999999379996.0 Const f_24_1 As Double = {(IsNetCoreApp ? "1.111111499991247E+20" : "1.1111114999912469E+20")} ' Dev11 & Roslyn: 1.1111114999912469E+20 ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. Const f_overflow_1 As Double = -1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Double = 1.79769313486231570E+309 ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Double = -4.94065645841246544E-326 ' Dev11: -0.0F, Roslyn: unchanged Const f_underflow_2 As Double = 4.94065645841246544E-326 ' Dev11: 0.0F, Roslyn: unchanged Console.WriteLine(f_17_1) Console.WriteLine(f_17_2) Console.WriteLine(f_17_3) Console.WriteLine(f_17_4) Console.WriteLine(f_17_5) Console.WriteLine(f_17_6) Console.WriteLine(f_17_7) Console.WriteLine(f_17_8) Console.WriteLine(f_18_1) Console.WriteLine(f_18_2) Console.WriteLine(f_18_3) Console.WriteLine(f_18_4) Console.WriteLine(f_18_5) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiterals_GreaterThan16Digits_WithTypeCharacter() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 3: > 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits ' (a) > 16 significant digits overall, but < 16 digits before decimal point. Const f_17_1 As Double = .14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_2 As Double = .14999999997999939r ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_3 As Double = .14999999997999937# ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_4 As Double = 0.1499999997999957R ' Dev11 & Roslyn: Unchanged Const f_17_5 As Double = 0.1499999997999958r ' Dev11 & Roslyn: 0.14999999979999579 Const f_17_6 As Double = 1.4999999997999947# ' Dev11 & Roslyn: Unchanged Const f_17_7 As Double = 1.4999999997999945R ' Dev11 & Roslyn: 1.4999999997999944 Const f_17_8 As Double = 1.4999999997999946r ' Dev11 & Roslyn: 1.4999999997999947 Const f_18_1 As Double = 14999999.9979999459# ' Dev11 & Roslyn: 14999999.997999946 Const f_18_2 As Double = 14999999.9979999451R ' Dev11 & Roslyn: 14999999.997999946 Const f_18_3 As Double = 14999999.9979999454r ' Dev11 & Roslyn: 14999999.997999946 ' (b) > 16 significant digits before decimal point. Const f_18_4 As Double = 14999999999733999.2# ' Dev11 & Roslyn: 1.4999999999734E+16 Const f_18_5 As Double = 14999999999379995.0R ' Dev11 & Roslyn: 14999999999379996.0 Const f_24_1 As Double = 111111149999124689999.499r ' Dev11 & Roslyn: 1.1111114999912469E+20 ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. Const f_overflow_1 As Double = -1.79769313486231570E+309# ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Double = 1.79769313486231570E+309R ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Double = -4.94065645841246544E-326r ' Dev11: -0.0F, Roslyn: unchanged Const f_underflow_2 As Double = 4.94065645841246544E-326# ' Dev11: 0.0F, Roslyn: unchanged Console.WriteLine(f_17_1) Console.WriteLine(f_17_2) Console.WriteLine(f_17_3) Console.WriteLine(f_17_4) Console.WriteLine(f_17_5) Console.WriteLine(f_17_6) Console.WriteLine(f_17_7) Console.WriteLine(f_17_8) Console.WriteLine(f_18_1) Console.WriteLine(f_18_2) Console.WriteLine(f_18_3) Console.WriteLine(f_18_4) Console.WriteLine(f_18_5) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' CATEGORY 3: > 16 significant digits ' Dev11 and Roslyn behavior are identical: Always rounded off and pretty listed to <= 17 significant digits ' (a) > 16 significant digits overall, but < 16 digits before decimal point. Const f_17_1 As Double = 0.14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_2 As Double = 0.14999999997999938R ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_3 As Double = 0.14999999997999938# ' Dev11 & Roslyn: 0.14999999997999938 Const f_17_4 As Double = 0.1499999997999957R ' Dev11 & Roslyn: Unchanged Const f_17_5 As Double = {(IsNetCoreApp ? "0.1499999997999958R" : "0.14999999979999579R")} ' Dev11 & Roslyn: 0.14999999979999579 Const f_17_6 As Double = 1.4999999997999947# ' Dev11 & Roslyn: Unchanged Const f_17_7 As Double = 1.4999999997999944R ' Dev11 & Roslyn: 1.4999999997999944 Const f_17_8 As Double = 1.4999999997999947R ' Dev11 & Roslyn: 1.4999999997999947 Const f_18_1 As Double = 14999999.997999946# ' Dev11 & Roslyn: 14999999.997999946 Const f_18_2 As Double = 14999999.997999946R ' Dev11 & Roslyn: 14999999.997999946 Const f_18_3 As Double = 14999999.997999946R ' Dev11 & Roslyn: 14999999.997999946 ' (b) > 16 significant digits before decimal point. Const f_18_4 As Double = {(IsNetCoreApp ? "14999999999734000.0#" : "1.4999999999734E+16#")} ' Dev11 & Roslyn: 1.4999999999734E+16 Const f_18_5 As Double = 14999999999379996.0R ' Dev11 & Roslyn: 14999999999379996.0 Const f_24_1 As Double = {(IsNetCoreApp ? "1.111111499991247E+20R" : "1.1111114999912469E+20R")} ' Dev11 & Roslyn: 1.1111114999912469E+20 ' (c) Overflow/Underflow cases for Double: Ensure no pretty listing/round off ' Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and ' from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. Const f_overflow_1 As Double = -1.79769313486231570E+309# ' Dev11 & Roslyn: Unchanged Const f_overflow_2 As Double = 1.79769313486231570E+309R ' Dev11 & Roslyn: Unchanged Const f_underflow_1 As Double = -4.94065645841246544E-326R ' Dev11: -0.0F, Roslyn: unchanged Const f_underflow_2 As Double = 4.94065645841246544E-326# ' Dev11: 0.0F, Roslyn: unchanged Console.WriteLine(f_17_1) Console.WriteLine(f_17_2) Console.WriteLine(f_17_3) Console.WriteLine(f_17_4) Console.WriteLine(f_17_5) Console.WriteLine(f_17_6) Console.WriteLine(f_17_7) Console.WriteLine(f_17_8) Console.WriteLine(f_18_1) Console.WriteLine(f_18_2) Console.WriteLine(f_18_3) Console.WriteLine(f_18_4) Console.WriteLine(f_18_5) Console.WriteLine(f_24_1) Console.WriteLine(f_overflow_1) Console.WriteLine(f_overflow_2) Console.WriteLine(f_underflow_1) Console.WriteLine(f_underflow_2) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiterals_LessThan30Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 30 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 27 significant digits Const d_27_1 As Decimal = .123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D Const d_27_2 As Decimal = 0.123456789012345678901234567d ' Dev11 & Roslyn: Unchanged Const d_27_3 As Decimal = 1.23456789012345678901234567D ' Dev11 & Roslyn: Unchanged Const d_27_4 As Decimal = 123456789012.345678901234567d ' Dev11 & Roslyn: Unchanged Const d_27_5 As Decimal = 12345678901234567890123456.7D ' Dev11 & Roslyn: Unchanged Const d_27_6 As Decimal = 123456789012345678901234567.0d ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D ' 29 significant digits Const d_29_1 As Decimal = .12345678901234567890123456789D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_29_2 As Decimal = 0.12345678901234567890123456789d ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_29_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: Unchanged Const d_29_4 As Decimal = 123456789012.34567890123456789d ' Dev11 & Roslyn: Unchanged Const d_29_5 As Decimal = 1234567890123456789012345678.9D ' Dev11 & Roslyn: Unchanged Const d_29_6 As Decimal = 12345678901234567890123456789.0d ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D Console.WriteLine(d_27_1) Console.WriteLine(d_27_2) Console.WriteLine(d_27_3) Console.WriteLine(d_27_4) Console.WriteLine(d_27_5) Console.WriteLine(d_27_6) Console.WriteLine(d_29_1) Console.WriteLine(d_29_2) Console.WriteLine(d_29_3) Console.WriteLine(d_29_4) Console.WriteLine(d_29_5) Console.WriteLine(d_29_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 30 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 27 significant digits Const d_27_1 As Decimal = 0.123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D Const d_27_2 As Decimal = 0.123456789012345678901234567D ' Dev11 & Roslyn: Unchanged Const d_27_3 As Decimal = 1.23456789012345678901234567D ' Dev11 & Roslyn: Unchanged Const d_27_4 As Decimal = 123456789012.345678901234567D ' Dev11 & Roslyn: Unchanged Const d_27_5 As Decimal = 12345678901234567890123456.7D ' Dev11 & Roslyn: Unchanged Const d_27_6 As Decimal = 123456789012345678901234567D ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D ' 29 significant digits Const d_29_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_29_2 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_29_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: Unchanged Const d_29_4 As Decimal = 123456789012.34567890123456789D ' Dev11 & Roslyn: Unchanged Const d_29_5 As Decimal = 1234567890123456789012345678.9D ' Dev11 & Roslyn: Unchanged Const d_29_6 As Decimal = 12345678901234567890123456789D ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D Console.WriteLine(d_27_1) Console.WriteLine(d_27_2) Console.WriteLine(d_27_3) Console.WriteLine(d_27_4) Console.WriteLine(d_27_5) Console.WriteLine(d_27_6) Console.WriteLine(d_29_1) Console.WriteLine(d_29_2) Console.WriteLine(d_29_3) Console.WriteLine(d_29_4) Console.WriteLine(d_29_5) Console.WriteLine(d_29_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiterals_LessThan30Digits_WithTypeCharacterDecimal() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 30 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 27 significant digits Const d_27_1 As Decimal = .123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D Const d_27_2 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_3 As Decimal = 1.23456789012345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_4 As Decimal = 123456789012.345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_5 As Decimal = 12345678901234567890123456.7@ ' Dev11 & Roslyn: Unchanged Const d_27_6 As Decimal = 123456789012345678901234567.0@ ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D ' 29 significant digits Const d_29_1 As Decimal = .12345678901234567890123456789@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ Const d_29_2 As Decimal = 0.12345678901234567890123456789@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ Const d_29_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: Unchanged Const d_29_4 As Decimal = 123456789012.34567890123456789@ ' Dev11 & Roslyn: Unchanged Const d_29_5 As Decimal = 1234567890123456789012345678.9@ ' Dev11 & Roslyn: Unchanged Const d_29_6 As Decimal = 12345678901234567890123456789.0@ ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D Console.WriteLine(d_27_1) Console.WriteLine(d_27_2) Console.WriteLine(d_27_3) Console.WriteLine(d_27_4) Console.WriteLine(d_27_5) Console.WriteLine(d_27_6) Console.WriteLine(d_29_1) Console.WriteLine(d_29_2) Console.WriteLine(d_29_3) Console.WriteLine(d_29_4) Console.WriteLine(d_29_5) Console.WriteLine(d_29_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 1: Less than 30 significant digits ' Dev11 and Roslyn behavior are identical: UNCHANGED ' 27 significant digits Const d_27_1 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 0.123456789012345678901234567D Const d_27_2 As Decimal = 0.123456789012345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_3 As Decimal = 1.23456789012345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_4 As Decimal = 123456789012.345678901234567@ ' Dev11 & Roslyn: Unchanged Const d_27_5 As Decimal = 12345678901234567890123456.7@ ' Dev11 & Roslyn: Unchanged Const d_27_6 As Decimal = 123456789012345678901234567@ ' Dev11 & Roslyn: Pretty listed to 123456789012345678901234567D ' 29 significant digits Const d_29_1 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ Const d_29_2 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679@ Const d_29_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: Unchanged Const d_29_4 As Decimal = 123456789012.34567890123456789@ ' Dev11 & Roslyn: Unchanged Const d_29_5 As Decimal = 1234567890123456789012345678.9@ ' Dev11 & Roslyn: Unchanged Const d_29_6 As Decimal = 12345678901234567890123456789@ ' Dev11 & Roslyn: Pretty listed to 12345678901234567890123456789D Console.WriteLine(d_27_1) Console.WriteLine(d_27_2) Console.WriteLine(d_27_3) Console.WriteLine(d_27_4) Console.WriteLine(d_27_5) Console.WriteLine(d_27_6) Console.WriteLine(d_29_1) Console.WriteLine(d_29_2) Console.WriteLine(d_29_3) Console.WriteLine(d_29_4) Console.WriteLine(d_29_5) Console.WriteLine(d_29_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiterals_30Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 30 significant digits ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits Const d_30_1 As Decimal = .123456789012345678901234567891D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_30_2 As Decimal = 0.1234567890123456789012345687891D ' Dev11 & Roslyn: 0.1234567890123456789012345688D Const d_30_3 As Decimal = 1.23456789012345678901234567891D ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_30_4 As Decimal = 123456789012345.678901234567891D ' Dev11 & Roslyn: 123456789012345.67890123456789D Const d_30_5 As Decimal = 12345678901234567890123456789.1D ' Dev11 & Roslyn: 12345678901234567890123456789D ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. Const d_30_6 As Decimal = 123456789012345678901234567891.0D ' Dev11 & Roslyn: 123456789012345678901234567891.0D Console.WriteLine(d_30_1) Console.WriteLine(d_30_2) Console.WriteLine(d_30_3) Console.WriteLine(d_30_4) Console.WriteLine(d_30_5) Console.WriteLine(d_30_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 2: 30 significant digits ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits Const d_30_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_30_2 As Decimal = 0.1234567890123456789012345688D ' Dev11 & Roslyn: 0.1234567890123456789012345688D Const d_30_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_30_4 As Decimal = 123456789012345.67890123456789D ' Dev11 & Roslyn: 123456789012345.67890123456789D Const d_30_5 As Decimal = 12345678901234567890123456789D ' Dev11 & Roslyn: 12345678901234567890123456789D ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. Const d_30_6 As Decimal = 123456789012345678901234567891.0D ' Dev11 & Roslyn: 123456789012345678901234567891.0D Console.WriteLine(d_30_1) Console.WriteLine(d_30_2) Console.WriteLine(d_30_3) Console.WriteLine(d_30_4) Console.WriteLine(d_30_5) Console.WriteLine(d_30_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiterals_30Digits_WithTypeCharacterDecimal() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 2: 30 significant digits ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits Const d_30_1 As Decimal = .123456789012345678901234567891@ ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_30_2 As Decimal = 0.1234567890123456789012345687891@ ' Dev11 & Roslyn: 0.1234567890123456789012345688D Const d_30_3 As Decimal = 1.23456789012345678901234567891@ ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_30_4 As Decimal = 123456789012345.678901234567891@ ' Dev11 & Roslyn: 123456789012345.67890123456789D Const d_30_5 As Decimal = 12345678901234567890123456789.1@ ' Dev11 & Roslyn: 12345678901234567890123456789D ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. Const d_30_6 As Decimal = 123456789012345678901234567891.0@ ' Dev11 & Roslyn: 123456789012345678901234567891.0D Console.WriteLine(d_30_1) Console.WriteLine(d_30_2) Console.WriteLine(d_30_3) Console.WriteLine(d_30_4) Console.WriteLine(d_30_5) Console.WriteLine(d_30_6) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 2: 30 significant digits ' Dev11 & Roslyn have identical behavior: pretty listed and round off to <= 29 significant digits Const d_30_1 As Decimal = 0.1234567890123456789012345679@ ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_30_2 As Decimal = 0.1234567890123456789012345688@ ' Dev11 & Roslyn: 0.1234567890123456789012345688D Const d_30_3 As Decimal = 1.2345678901234567890123456789@ ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_30_4 As Decimal = 123456789012345.67890123456789@ ' Dev11 & Roslyn: 123456789012345.67890123456789D Const d_30_5 As Decimal = 12345678901234567890123456789@ ' Dev11 & Roslyn: 12345678901234567890123456789D ' Overflow case 30 significant digits before decimal place: Ensure no pretty listing. Const d_30_6 As Decimal = 123456789012345678901234567891.0@ ' Dev11 & Roslyn: 123456789012345678901234567891.0D Console.WriteLine(d_30_1) Console.WriteLine(d_30_2) Console.WriteLine(d_30_3) Console.WriteLine(d_30_4) Console.WriteLine(d_30_5) Console.WriteLine(d_30_6) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiterals_GreaterThan30Digits() { var code = @"[| Module Program Sub Main(args As String()) ' CATEGORY 3: > 30 significant digits ' Dev11 has unpredictable behavior: pretty listed/round off to wrong values in certain cases ' Roslyn behavior: Always rounded off + pretty listed to <= 29 significant digits ' (a) > 30 significant digits overall, but < 30 digits before decimal point. Const d_32_1 As Decimal = .12345678901234567890123456789012D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_32_2 As Decimal = 0.123456789012345678901234568789012@ ' Dev11 & Roslyn: 0.1234567890123456789012345688@ Const d_32_3 As Decimal = 1.2345678901234567890123456789012d ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_32_4 As Decimal = 123456789012345.67890123456789012@ ' Dev11 & Roslyn: 123456789012345.67890123456789@ ' (b) > 30 significant digits before decimal point (Overflow case): Ensure no pretty listing. Const d_35_1 As Decimal = 123456789012345678901234567890123.45D ' Dev11 & Roslyn: 123456789012345678901234567890123.45D Console.WriteLine(d_32_1) Console.WriteLine(d_32_2) Console.WriteLine(d_32_3) Console.WriteLine(d_32_4) Console.WriteLine(d_35_1) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) ' CATEGORY 3: > 30 significant digits ' Dev11 has unpredictable behavior: pretty listed/round off to wrong values in certain cases ' Roslyn behavior: Always rounded off + pretty listed to <= 29 significant digits ' (a) > 30 significant digits overall, but < 30 digits before decimal point. Const d_32_1 As Decimal = 0.1234567890123456789012345679D ' Dev11 & Roslyn: 0.1234567890123456789012345679D Const d_32_2 As Decimal = 0.1234567890123456789012345688@ ' Dev11 & Roslyn: 0.1234567890123456789012345688@ Const d_32_3 As Decimal = 1.2345678901234567890123456789D ' Dev11 & Roslyn: 1.2345678901234567890123456789D Const d_32_4 As Decimal = 123456789012345.67890123456789@ ' Dev11 & Roslyn: 123456789012345.67890123456789@ ' (b) > 30 significant digits before decimal point (Overflow case): Ensure no pretty listing. Const d_35_1 As Decimal = 123456789012345678901234567890123.45D ' Dev11 & Roslyn: 123456789012345678901234567890123.45D Console.WriteLine(d_32_1) Console.WriteLine(d_32_2) Console.WriteLine(d_32_3) Console.WriteLine(d_32_4) Console.WriteLine(d_35_1) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceFloatLiteralsWithNegativeExponents() { var code = @"[| Module Program Sub Main(args As String()) ' Floating point values might be represented either in fixed point notation or scientific/exponent notation. ' MSDN comment for Standard Numeric Format Strings used in Single.ToString(String) API (or Double.ToString(String)): ' Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and ' less than the precision specifier; otherwise, scientific notation is used. ' ' However, Dev11 pretty lister differs from this for floating point values < 0. It uses fixed point notation as long as exponent is greater than '-(actualPrecision + 1)'. ' For example, consider Single Floating literals: ' (i) Precision = 7 ' 0.0000001234567F => 0.0000001234567F (exponent = -7: fixed point notation) ' 0.00000001234567F => 0.00000001234567F (exponent = -8: fixed point notation) ' 0.000000001234567F => 1.234567E-9F (exponent = -9: exponent notation) ' 0.0000000001234567F => 1.234567E-10F (exponent = -10: exponent notation) ' (ii) Precision = 9 ' 0.0000000012345678F => 0.00000000123456778F (exponent = -9: fixed point notation) ' 0.00000000012345678F => 0.000000000123456786F (exponent = -10: fixed point notation) ' 0.000000000012345678F => 1.23456783E-11F (exponent = -11: exponent notation) ' 0.0000000000012345678F => 1.23456779E-12F (exponent = -12: exponent notation) Const f_1 As Single = 0.000001234567F Const f_2 As Single = 0.0000001234567F Const f_3 As Single = 0.00000001234567F Const f_4 As Single = 0.000000001234567F ' Change at -9 Const f_5 As Single = 0.0000000001234567F Const f_6 As Single = 0.00000000123456778F Const f_7 As Single = 0.000000000123456786F Const f_8 As Single = 0.000000000012345678F ' Change at -11 Const f_9 As Single = 0.0000000000012345678F Const d_1 As Single = 0.00000000000000123456789012345 Const d_2 As Single = 0.000000000000000123456789012345 Const d_3 As Single = 0.0000000000000000123456789012345 ' Change at -17 Const d_4 As Single = 0.00000000000000000123456789012345 Const d_5 As Double = 0.00000000000000001234567890123456 Const d_6 As Double = 0.000000000000000001234567890123456 Const d_7 As Double = 0.0000000000000000001234567890123456 ' Change at -19 Const d_8 As Double = 0.00000000000000000001234567890123456 End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) ' Floating point values might be represented either in fixed point notation or scientific/exponent notation. ' MSDN comment for Standard Numeric Format Strings used in Single.ToString(String) API (or Double.ToString(String)): ' Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and ' less than the precision specifier; otherwise, scientific notation is used. ' ' However, Dev11 pretty lister differs from this for floating point values < 0. It uses fixed point notation as long as exponent is greater than '-(actualPrecision + 1)'. ' For example, consider Single Floating literals: ' (i) Precision = 7 ' 0.0000001234567F => 0.0000001234567F (exponent = -7: fixed point notation) ' 0.00000001234567F => 0.00000001234567F (exponent = -8: fixed point notation) ' 0.000000001234567F => 1.234567E-9F (exponent = -9: exponent notation) ' 0.0000000001234567F => 1.234567E-10F (exponent = -10: exponent notation) ' (ii) Precision = 9 ' 0.0000000012345678F => 0.00000000123456778F (exponent = -9: fixed point notation) ' 0.00000000012345678F => 0.000000000123456786F (exponent = -10: fixed point notation) ' 0.000000000012345678F => 1.23456783E-11F (exponent = -11: exponent notation) ' 0.0000000000012345678F => 1.23456779E-12F (exponent = -12: exponent notation) Const f_1 As Single = 0.000001234567F Const f_2 As Single = 0.0000001234567F Const f_3 As Single = 0.00000001234567F Const f_4 As Single = 1.234567E-9F ' Change at -9 Const f_5 As Single = 1.234567E-10F Const f_6 As Single = {(IsNetCoreApp ? "0.0000000012345678F" : "0.00000000123456778F")} Const f_7 As Single = {(IsNetCoreApp ? "0.00000000012345679F" : "0.000000000123456786F")} Const f_8 As Single = {(IsNetCoreApp ? "1.2345678E-11F" : "1.23456783E-11F")} ' Change at -11 Const f_9 As Single = {(IsNetCoreApp ? "1.2345678E-12F" : "1.23456779E-12F")} Const d_1 As Single = 0.00000000000000123456789012345 Const d_2 As Single = 0.000000000000000123456789012345 Const d_3 As Single = 1.23456789012345E-17 ' Change at -17 Const d_4 As Single = 1.23456789012345E-18 Const d_5 As Double = {(IsNetCoreApp ? "0.00000000000000001234567890123456" : "0.000000000000000012345678901234561")} Const d_6 As Double = 0.000000000000000001234567890123456 Const d_7 As Double = {(IsNetCoreApp ? "1.234567890123456E-19" : "1.2345678901234561E-19")} ' Change at -19 Const d_8 As Double = 1.234567890123456E-20 End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceSingleLiteralsWithTrailingZeros() { var code = @"[| Module Program Sub Main(args As String()) Const f1 As Single = 3.011000F ' Dev11 & Roslyn: 3.011F Const f2 As Single = 3.000000! ' Dev11 & Roslyn: 3.0! Const f3 As Single = 3.0F ' Dev11 & Roslyn: Unchanged Const f4 As Single = 3000f ' Dev11 & Roslyn: 3000.0F Const f5 As Single = 3000E+10! ' Dev11 & Roslyn: 3.0E+13! Const f6 As Single = 3000.0E+10F ' Dev11 & Roslyn: 3.0E+13F Const f7 As Single = 3000.010E+1F ' Dev11 & Roslyn: 30000.1F Const f8 As Single = 3000.123456789010E+10! ' Dev11 & Roslyn: 3.00012337E+13! Const f9 As Single = 3000.123456789000E+10F ' Dev11 & Roslyn: 3.00012337E+13F Const f10 As Single = 30001234567890.10E-10f ' Dev11 & Roslyn: 3000.12354F Const f11 As Single = 3000E-10! ' Dev11 & Roslyn: 0.0000003! Console.WriteLine(f1) Console.WriteLine(f2) Console.WriteLine(f3) Console.WriteLine(f4) Console.WriteLine(f5) Console.WriteLine(f6) Console.WriteLine(f7) Console.WriteLine(f8) Console.WriteLine(f9) Console.WriteLine(f10) Console.WriteLine(f11) End Sub End Module |]"; var expected = $@" Module Program Sub Main(args As String()) Const f1 As Single = 3.011F ' Dev11 & Roslyn: 3.011F Const f2 As Single = 3.0! ' Dev11 & Roslyn: 3.0! Const f3 As Single = 3.0F ' Dev11 & Roslyn: Unchanged Const f4 As Single = 3000.0F ' Dev11 & Roslyn: 3000.0F Const f5 As Single = 3.0E+13! ' Dev11 & Roslyn: 3.0E+13! Const f6 As Single = 3.0E+13F ' Dev11 & Roslyn: 3.0E+13F Const f7 As Single = 30000.1F ' Dev11 & Roslyn: 30000.1F Const f8 As Single = {(IsNetCoreApp ? "3.0001234E+13!" : "3.00012337E+13!")} ' Dev11 & Roslyn: 3.00012337E+13! Const f9 As Single = {(IsNetCoreApp ? "3.0001234E+13F" : "3.00012337E+13F")} ' Dev11 & Roslyn: 3.00012337E+13F Const f10 As Single = {(IsNetCoreApp ? "3000.1235F" : "3000.12354F")} ' Dev11 & Roslyn: 3000.12354F Const f11 As Single = 0.0000003! ' Dev11 & Roslyn: 0.0000003! Console.WriteLine(f1) Console.WriteLine(f2) Console.WriteLine(f3) Console.WriteLine(f4) Console.WriteLine(f5) Console.WriteLine(f6) Console.WriteLine(f7) Console.WriteLine(f8) Console.WriteLine(f9) Console.WriteLine(f10) Console.WriteLine(f11) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDoubleLiteralsWithTrailingZeros() { var code = @"[| Module Program Sub Main(args As String()) Const d1 As Double = 3.011000 ' Dev11 & Roslyn: 3.011 Const d2 As Double = 3.000000 ' Dev11 & Roslyn: 3.0 Const d3 As Double = 3.0 ' Dev11 & Roslyn: Unchanged Const d4 As Double = 3000R ' Dev11 & Roslyn: 3000.0R Const d5 As Double = 3000E+10# ' Dev11 & Roslyn: 30000000000000.0# Const d6 As Double = 3000.0E+10 ' Dev11 & Roslyn: 30000000000000.0 Const d7 As Double = 3000.010E+1 ' Dev11 & Roslyn: 30000.1 Const d8 As Double = 3000.123456789010E+10# ' Dev11 & Roslyn: 30001234567890.1# Const d9 As Double = 3000.123456789000E+10 ' Dev11 & Roslyn: 30001234567890.0 Const d10 As Double = 30001234567890.10E-10d ' Dev11 & Roslyn: 3000.12345678901D Const d11 As Double = 3000E-10 ' Dev11 & Roslyn: 0.0000003 Console.WriteLine(d1) Console.WriteLine(d2) Console.WriteLine(d3) Console.WriteLine(d4) Console.WriteLine(d5) Console.WriteLine(d6) Console.WriteLine(d7) Console.WriteLine(d8) Console.WriteLine(d9) Console.WriteLine(d10) Console.WriteLine(d11) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) Const d1 As Double = 3.011 ' Dev11 & Roslyn: 3.011 Const d2 As Double = 3.0 ' Dev11 & Roslyn: 3.0 Const d3 As Double = 3.0 ' Dev11 & Roslyn: Unchanged Const d4 As Double = 3000.0R ' Dev11 & Roslyn: 3000.0R Const d5 As Double = 30000000000000.0# ' Dev11 & Roslyn: 30000000000000.0# Const d6 As Double = 30000000000000.0 ' Dev11 & Roslyn: 30000000000000.0 Const d7 As Double = 30000.1 ' Dev11 & Roslyn: 30000.1 Const d8 As Double = 30001234567890.1# ' Dev11 & Roslyn: 30001234567890.1# Const d9 As Double = 30001234567890.0 ' Dev11 & Roslyn: 30001234567890.0 Const d10 As Double = 3000.12345678901D ' Dev11 & Roslyn: 3000.12345678901D Const d11 As Double = 0.0000003 ' Dev11 & Roslyn: 0.0000003 Console.WriteLine(d1) Console.WriteLine(d2) Console.WriteLine(d3) Console.WriteLine(d4) Console.WriteLine(d5) Console.WriteLine(d6) Console.WriteLine(d7) Console.WriteLine(d8) Console.WriteLine(d9) Console.WriteLine(d10) Console.WriteLine(d11) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5529, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceDecimalLiteralsWithTrailingZeros() { var code = @"[| Module Program Sub Main(args As String()) Const d1 As Decimal = 3.011000D ' Dev11 & Roslyn: 3.011D Const d2 As Decimal = 3.000000D ' Dev11 & Roslyn: 3D Const d3 As Decimal = 3.0D ' Dev11 & Roslyn: 3D Const d4 As Decimal = 3000D ' Dev11 & Roslyn: 3000D Const d5 As Decimal = 3000E+10D ' Dev11 & Roslyn: 30000000000000D Const d6 As Decimal = 3000.0E+10D ' Dev11 & Roslyn: 30000000000000D Const d7 As Decimal = 3000.010E+1D ' Dev11 & Roslyn: 30000.1D Const d8 As Decimal = 3000.123456789010E+10D ' Dev11 & Roslyn: 30001234567890.1D Const d9 As Decimal = 3000.123456789000E+10D ' Dev11 & Roslyn: 30001234567890D Const d10 As Decimal = 30001234567890.10E-10D ' Dev11 & Roslyn: 3000.12345678901D Const d11 As Decimal = 3000E-10D ' Dev11 & Roslyn: 0.0000003D Console.WriteLine(d1) Console.WriteLine(d2) Console.WriteLine(d3) Console.WriteLine(d4) Console.WriteLine(d5) Console.WriteLine(d6) Console.WriteLine(d7) Console.WriteLine(d8) Console.WriteLine(d9) Console.WriteLine(d10) Console.WriteLine(d11) End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) Const d1 As Decimal = 3.011D ' Dev11 & Roslyn: 3.011D Const d2 As Decimal = 3D ' Dev11 & Roslyn: 3D Const d3 As Decimal = 3D ' Dev11 & Roslyn: 3D Const d4 As Decimal = 3000D ' Dev11 & Roslyn: 3000D Const d5 As Decimal = 30000000000000D ' Dev11 & Roslyn: 30000000000000D Const d6 As Decimal = 30000000000000D ' Dev11 & Roslyn: 30000000000000D Const d7 As Decimal = 30000.1D ' Dev11 & Roslyn: 30000.1D Const d8 As Decimal = 30001234567890.1D ' Dev11 & Roslyn: 30001234567890.1D Const d9 As Decimal = 30001234567890D ' Dev11 & Roslyn: 30001234567890D Const d10 As Decimal = 3000.12345678901D ' Dev11 & Roslyn: 3000.12345678901D Const d11 As Decimal = 0.0000003D ' Dev11 & Roslyn: 0.0000003D Console.WriteLine(d1) Console.WriteLine(d2) Console.WriteLine(d3) Console.WriteLine(d4) Console.WriteLine(d5) Console.WriteLine(d6) Console.WriteLine(d7) Console.WriteLine(d8) Console.WriteLine(d9) Console.WriteLine(d10) Console.WriteLine(d11) End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(623319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623319")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceFloatingAndDecimalLiteralsWithDifferentCulture() { var savedCulture = System.Threading.Thread.CurrentThread.CurrentCulture; try { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"); var code = @"[| Module Program Sub Main(args As String()) Dim d = 1.0D Dim f = 1.0F Dim x = 1.0 End Sub End Module|]"; var expected = @" Module Program Sub Main(args As String()) Dim d = 1D Dim f = 1.0F Dim x = 1.0 End Sub End Module"; await VerifyAsync(code, expected); } finally { System.Threading.Thread.CurrentThread.CurrentCulture = savedCulture; } } [Fact] [WorkItem(652147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/652147")] public async Task ReduceFloatingAndDecimalLiteralsWithInvariantCultureNegatives() { var oldCulture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = (CultureInfo)oldCulture.Clone(); Thread.CurrentThread.CurrentCulture.NumberFormat.NegativeSign = "~"; var code = @"[| Module Program Sub Main(args As String()) Dim d = -1.0E-11D Dim f = -1.0E-11F Dim x = -1.0E-11 End Sub End Module|]"; var expected = @" Module Program Sub Main(args As String()) Dim d = -0.00000000001D Dim f = -1.0E-11F Dim x = -0.00000000001 End Sub End Module"; await VerifyAsync(code, expected); } finally { Thread.CurrentThread.CurrentCulture = oldCulture; } } [Fact] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceIntegerLiteralWithLeadingZeros() { var code = @"[| Module Program Sub Main(args As String()) Const i0 As Integer = 0060 Const i1 As Integer = 0060% Const i2 As Integer = &H006F Const i3 As Integer = &O0060 Const i4 As Integer = 0060I Const i5 As Integer = -0060 Const i6 As Integer = 000 Const i7 As UInteger = 0060UI Const i8 As Integer = &H0000FFFFI Const i9 As Integer = &O000 Const i10 As Integer = &H000 Const l0 As Long = 0060L Const l1 As Long = 0060& Const l2 As ULong = 0060UL Const s0 As Short = 0060S Const s1 As UShort = 0060US Const s2 As Short = &H0000FFFFS End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) Const i0 As Integer = 60 Const i1 As Integer = 60% Const i2 As Integer = &H6F Const i3 As Integer = &O60 Const i4 As Integer = 60I Const i5 As Integer = -60 Const i6 As Integer = 0 Const i7 As UInteger = 60UI Const i8 As Integer = &HFFFFI Const i9 As Integer = &O0 Const i10 As Integer = &H0 Const l0 As Long = 60L Const l1 As Long = 60& Const l2 As ULong = 60UL Const s0 As Short = 60S Const s1 As UShort = 60US Const s2 As Short = &HFFFFS End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceIntegerLiteralWithNegativeHexOrOctalValue() { var code = @"[| Module Program Sub Main(args As String()) Const s0 As Short = &HFFFFS Const s1 As Short = &O177777S Const s2 As Short = &H8000S Const s3 As Short = &O100000S Const i0 As Integer = &O37777777777I Const i1 As Integer = &HFFFFFFFFI Const i2 As Integer = &H80000000I Const i3 As Integer = &O20000000000I Const l0 As Long = &HFFFFFFFFFFFFFFFFL Const l1 As Long = &O1777777777777777777777L Const l2 As Long = &H8000000000000000L Const l2 As Long = &O1000000000000000000000L End Sub End Module |]"; var expected = @" Module Program Sub Main(args As String()) Const s0 As Short = &HFFFFS Const s1 As Short = &O177777S Const s2 As Short = &H8000S Const s3 As Short = &O100000S Const i0 As Integer = &O37777777777I Const i1 As Integer = &HFFFFFFFFI Const i2 As Integer = &H80000000I Const i3 As Integer = &O20000000000I Const l0 As Long = &HFFFFFFFFFFFFFFFFL Const l1 As Long = &O1777777777777777777777L Const l2 As Long = &H8000000000000000L Const l2 As Long = &O1000000000000000000000L End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceIntegerLiteralWithOverflow() { var code = @"[| Module Module1 Sub Main() Dim sMax As Short = 0032768S Dim usMax As UShort = 00655536US Dim iMax As Integer = 002147483648I Dim uiMax As UInteger = 004294967296UI Dim lMax As Long = 009223372036854775808L Dim ulMax As ULong = 0018446744073709551616UL Dim z As Long = &O37777777777777777777777 Dim x As Long = &HFFFFFFFFFFFFFFFFF End Sub End Module |]"; var expected = @" Module Module1 Sub Main() Dim sMax As Short = 0032768S Dim usMax As UShort = 00655536US Dim iMax As Integer = 002147483648I Dim uiMax As UInteger = 004294967296UI Dim lMax As Long = 009223372036854775808L Dim ulMax As ULong = 0018446744073709551616UL Dim z As Long = &O37777777777777777777777 Dim x As Long = &HFFFFFFFFFFFFFFFFF End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task ReduceBinaryIntegerLiteral() { var code = @"[| Module Module1 Sub Main() ' signed Dim a As SByte = &B0111 Dim b As Short = &B0101 Dim c As Integer = &B00100100 Dim d As Long = &B001001100110 ' unsigned Dim e As Byte = &B01011 Dim f As UShort = &B00100 Dim g As UInteger = &B001001100110 Dim h As ULong = &B001001100110 ' negative Dim i As SByte = -&B0111 Dim j As Short = -&B00101 Dim k As Integer = -&B00100100 Dim l As Long = -&B001001100110 ' negative literal Dim m As SByte = &B10000001 Dim n As Short = &B1000000000000001 Dim o As Integer = &B10000000000000000000000000000001 Dim p As Long = &B1000000000000000000000000000000000000000000000000000000000000001 End Sub End Module |]"; var expected = @" Module Module1 Sub Main() ' signed Dim a As SByte = &B111 Dim b As Short = &B101 Dim c As Integer = &B100100 Dim d As Long = &B1001100110 ' unsigned Dim e As Byte = &B1011 Dim f As UShort = &B100 Dim g As UInteger = &B1001100110 Dim h As ULong = &B1001100110 ' negative Dim i As SByte = -&B111 Dim j As Short = -&B101 Dim k As Integer = -&B100100 Dim l As Long = -&B1001100110 ' negative literal Dim m As SByte = &B10000001 Dim n As Short = &B1000000000000001 Dim o As Integer = &B10000000000000000000000000000001 Dim p As Long = &B1000000000000000000000000000000000000000000000000000000000000001 End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(14034, "https://github.com/dotnet/roslyn/issues/14034")] [WorkItem(48492, "https://github.com/dotnet/roslyn/issues/48492")] [Trait(Traits.Feature, Traits.Features.ReduceTokens)] public async Task DoNotReduceDigitSeparators() { var source = @" Module Module1 Sub Main() Dim x = 100_000 Dim y = 100_000.0F Dim z = 100_000.0D End Sub End Module "; var expected = source; await VerifyAsync($"[|{source}|]", expected); } private static async Task VerifyAsync(string codeWithMarker, string expectedResult) { MarkupTestFile.GetSpans(codeWithMarker, out var codeWithoutMarker, out ImmutableArray<TextSpan> textSpans); var document = CreateDocument(codeWithoutMarker, LanguageNames.VisualBasic); var codeCleanups = CodeCleaner.GetDefaultProviders(document).WhereAsArray(p => p.Name == PredefinedCodeCleanupProviderNames.ReduceTokens || p.Name == PredefinedCodeCleanupProviderNames.CaseCorrection || p.Name == PredefinedCodeCleanupProviderNames.Format); var cleanDocument = await CodeCleaner.CleanupAsync(document, textSpans[0], codeCleanups); AssertEx.EqualOrDiff(expectedResult, (await cleanDocument.GetSyntaxRootAsync()).ToFullString()); } private static Document CreateDocument(string code, string language) { var solution = new AdhocWorkspace().CurrentSolution; var projectId = ProjectId.CreateNewId(); var project = solution.AddProject(projectId, "Project", "Project.dll", language).GetProject(projectId); return project.AddMetadataReference(TestMetadata.Net451.mscorlib) .AddDocument("Document", SourceText.From(code)); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpOutlining.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpOutlining : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpOutlining(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpOutlining)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void Outlining() { var input = @" using [|System; using System.Collections.Generic; using System.Text;|] namespace ConsoleApplication1[| { public class Program[| { public static void Main(string[] args)[| { Console.WriteLine(""Hello World""); }|] }|] }|]"; MarkupTestFile.GetSpans(input, out var text, out ImmutableArray<TextSpan> spans); VisualStudio.Editor.SetText(text); Assert.Equal(spans.OrderBy(s => s.Start), VisualStudio.Editor.GetOutliningSpans()); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void OutliningConfigChange() { var input = @" namespace ClassLibrary1[| { public class Class1[| { #if DEBUG {|Release: void Goo(){|Debug: { }|} void Goo2(){|Debug: { }|}|} #else {|Debug: void Bar(){|Release: { }|}|} #endif }|] }|]"; MarkupTestFile.GetSpans(input, out var text, out IDictionary<string, ImmutableArray<TextSpan>> spans); VisualStudio.Editor.SetText(text); VerifySpansInConfiguration(spans, "Release"); VerifySpansInConfiguration(spans, "Debug"); } private void VerifySpansInConfiguration(IDictionary<string, ImmutableArray<TextSpan>> spans, string configuration) { VisualStudio.ExecuteCommand("Build.SolutionConfigurations", configuration); var expectedSpans = spans[""].Concat(spans[configuration]).OrderBy(s => s.Start); Assert.Equal(expectedSpans, VisualStudio.Editor.GetOutliningSpans()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpOutlining : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpOutlining(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpOutlining)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void Outlining() { var input = @" using [|System; using System.Collections.Generic; using System.Text;|] namespace ConsoleApplication1[| { public class Program[| { public static void Main(string[] args)[| { Console.WriteLine(""Hello World""); }|] }|] }|]"; MarkupTestFile.GetSpans(input, out var text, out ImmutableArray<TextSpan> spans); VisualStudio.Editor.SetText(text); Assert.Equal(spans.OrderBy(s => s.Start), VisualStudio.Editor.GetOutliningSpans()); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public void OutliningConfigChange() { var input = @" namespace ClassLibrary1[| { public class Class1[| { #if DEBUG {|Release: void Goo(){|Debug: { }|} void Goo2(){|Debug: { }|}|} #else {|Debug: void Bar(){|Release: { }|}|} #endif }|] }|]"; MarkupTestFile.GetSpans(input, out var text, out IDictionary<string, ImmutableArray<TextSpan>> spans); VisualStudio.Editor.SetText(text); VerifySpansInConfiguration(spans, "Release"); VerifySpansInConfiguration(spans, "Debug"); } private void VerifySpansInConfiguration(IDictionary<string, ImmutableArray<TextSpan>> spans, string configuration) { VisualStudio.ExecuteCommand("Build.SolutionConfigurations", configuration); var expectedSpans = spans[""].Concat(spans[configuration]).OrderBy(s => s.Start); Assert.Equal(expectedSpans, VisualStudio.Editor.GetOutliningSpans()); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/Core/ModernCommands/GoToImplementationCommandArgs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; namespace Microsoft.CodeAnalysis.Editor.Commanding.Commands { /// <summary> /// Arguments for Go To Implementation. /// </summary> [ExcludeFromCodeCoverage] internal sealed class GoToImplementationCommandArgs : EditorCommandArgs { public GoToImplementationCommandArgs(ITextView textView, ITextBuffer subjectBuffer) : base(textView, subjectBuffer) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; namespace Microsoft.CodeAnalysis.Editor.Commanding.Commands { /// <summary> /// Arguments for Go To Implementation. /// </summary> [ExcludeFromCodeCoverage] internal sealed class GoToImplementationCommandArgs : EditorCommandArgs { public GoToImplementationCommandArgs(ITextView textView, ITextBuffer subjectBuffer) : base(textView, subjectBuffer) { } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/IRegexNodeVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.EmbeddedLanguages.RegularExpressions { internal interface IRegexNodeVisitor { void Visit(RegexCompilationUnit node); void Visit(RegexSequenceNode node); void Visit(RegexTextNode node); void Visit(RegexCharacterClassNode node); void Visit(RegexNegatedCharacterClassNode node); void Visit(RegexCharacterClassRangeNode node); void Visit(RegexCharacterClassSubtractionNode node); void Visit(RegexPosixPropertyNode node); void Visit(RegexWildcardNode node); void Visit(RegexZeroOrMoreQuantifierNode node); void Visit(RegexOneOrMoreQuantifierNode node); void Visit(RegexZeroOrOneQuantifierNode node); void Visit(RegexLazyQuantifierNode node); void Visit(RegexExactNumericQuantifierNode node); void Visit(RegexOpenNumericRangeQuantifierNode node); void Visit(RegexClosedNumericRangeQuantifierNode node); void Visit(RegexAnchorNode node); void Visit(RegexAlternationNode node); void Visit(RegexSimpleGroupingNode node); void Visit(RegexSimpleOptionsGroupingNode node); void Visit(RegexNestedOptionsGroupingNode node); void Visit(RegexNonCapturingGroupingNode node); void Visit(RegexPositiveLookaheadGroupingNode node); void Visit(RegexNegativeLookaheadGroupingNode node); void Visit(RegexPositiveLookbehindGroupingNode node); void Visit(RegexNegativeLookbehindGroupingNode node); void Visit(RegexAtomicGroupingNode node); void Visit(RegexCaptureGroupingNode node); void Visit(RegexBalancingGroupingNode node); void Visit(RegexConditionalCaptureGroupingNode node); void Visit(RegexConditionalExpressionGroupingNode node); void Visit(RegexSimpleEscapeNode node); void Visit(RegexAnchorEscapeNode node); void Visit(RegexCharacterClassEscapeNode node); void Visit(RegexControlEscapeNode node); void Visit(RegexHexEscapeNode node); void Visit(RegexUnicodeEscapeNode node); void Visit(RegexCaptureEscapeNode node); void Visit(RegexKCaptureEscapeNode node); void Visit(RegexOctalEscapeNode node); void Visit(RegexBackreferenceEscapeNode node); void Visit(RegexCategoryEscapeNode node); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions { internal interface IRegexNodeVisitor { void Visit(RegexCompilationUnit node); void Visit(RegexSequenceNode node); void Visit(RegexTextNode node); void Visit(RegexCharacterClassNode node); void Visit(RegexNegatedCharacterClassNode node); void Visit(RegexCharacterClassRangeNode node); void Visit(RegexCharacterClassSubtractionNode node); void Visit(RegexPosixPropertyNode node); void Visit(RegexWildcardNode node); void Visit(RegexZeroOrMoreQuantifierNode node); void Visit(RegexOneOrMoreQuantifierNode node); void Visit(RegexZeroOrOneQuantifierNode node); void Visit(RegexLazyQuantifierNode node); void Visit(RegexExactNumericQuantifierNode node); void Visit(RegexOpenNumericRangeQuantifierNode node); void Visit(RegexClosedNumericRangeQuantifierNode node); void Visit(RegexAnchorNode node); void Visit(RegexAlternationNode node); void Visit(RegexSimpleGroupingNode node); void Visit(RegexSimpleOptionsGroupingNode node); void Visit(RegexNestedOptionsGroupingNode node); void Visit(RegexNonCapturingGroupingNode node); void Visit(RegexPositiveLookaheadGroupingNode node); void Visit(RegexNegativeLookaheadGroupingNode node); void Visit(RegexPositiveLookbehindGroupingNode node); void Visit(RegexNegativeLookbehindGroupingNode node); void Visit(RegexAtomicGroupingNode node); void Visit(RegexCaptureGroupingNode node); void Visit(RegexBalancingGroupingNode node); void Visit(RegexConditionalCaptureGroupingNode node); void Visit(RegexConditionalExpressionGroupingNode node); void Visit(RegexSimpleEscapeNode node); void Visit(RegexAnchorEscapeNode node); void Visit(RegexCharacterClassEscapeNode node); void Visit(RegexControlEscapeNode node); void Visit(RegexHexEscapeNode node); void Visit(RegexUnicodeEscapeNode node); void Visit(RegexCaptureEscapeNode node); void Visit(RegexKCaptureEscapeNode node); void Visit(RegexOctalEscapeNode node); void Visit(RegexBackreferenceEscapeNode node); void Visit(RegexCategoryEscapeNode node); } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Clr.NativeCompilation; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class DkmUtilities { internal unsafe delegate IntPtr GetMetadataBytesPtrFunction(AssemblyIdentity assemblyIdentity, out uint uSize); // Return the set of managed module instances from the AppDomain. private static IEnumerable<DkmClrModuleInstance> GetModulesInAppDomain(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain) { if (appDomain.IsUnloaded) { return SpecializedCollections.EmptyEnumerable<DkmClrModuleInstance>(); } var appDomainId = appDomain.Id; // GetModuleInstances() may include instances of DkmClrNcContainerModuleInstance // which are containers of managed module instances (see GetEmbeddedModules()) // but not managed modules themselves. Since GetModuleInstances() will include the // embedded modules, we can simply ignore DkmClrNcContainerModuleInstances. return runtime.GetModuleInstances(). OfType<DkmClrModuleInstance>(). Where(module => { var moduleAppDomain = module.AppDomain; return !moduleAppDomain.IsUnloaded && (moduleAppDomain.Id == appDomainId); }); } internal static ImmutableArray<MetadataBlock> GetMetadataBlocks( this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain, ImmutableArray<MetadataBlock> previousMetadataBlocks) { // Add a dummy data item to the appdomain to add it to the disposal queue when the debugged process is shutting down. // This should prevent from attempts to use the Metadata pointer for dead debugged processes. if (appDomain.GetDataItem<AppDomainLifetimeDataItem>() == null) { appDomain.SetDataItem(DkmDataCreationDisposition.CreateNew, new AppDomainLifetimeDataItem()); } var builder = ArrayBuilder<MetadataBlock>.GetInstance(); IntPtr ptr; uint size; int index = 0; foreach (DkmClrModuleInstance module in runtime.GetModulesInAppDomain(appDomain)) { MetadataBlock block; try { ptr = module.GetMetaDataBytesPtr(out size); Debug.Assert(size > 0); block = GetMetadataBlock(previousMetadataBlocks, index, ptr, size); } catch (NotImplementedException e) when (module is DkmClrNcModuleInstance) { // DkmClrNcModuleInstance.GetMetaDataBytesPtr not implemented in Dev14. throw new NotImplementedMetadataException(e); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } Debug.Assert(block.ModuleVersionId == module.Mvid); builder.Add(block); index++; } // Include "intrinsic method" assembly. ptr = runtime.GetIntrinsicAssemblyMetaDataBytesPtr(out size); builder.Add(GetMetadataBlock(previousMetadataBlocks, index, ptr, size)); return builder.ToImmutableAndFree(); } internal static ImmutableArray<MetadataBlock> GetMetadataBlocks(GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities) { ArrayBuilder<MetadataBlock>? builder = null; foreach (var missingAssemblyIdentity in missingAssemblyIdentities) { MetadataBlock block; try { uint size; IntPtr ptr; ptr = getMetaDataBytesPtrFunction(missingAssemblyIdentity, out size); Debug.Assert(size > 0); block = GetMetadataBlock(ptr, size); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } if (builder == null) { builder = ArrayBuilder<MetadataBlock>.GetInstance(); } builder.Add(block); } return builder == null ? ImmutableArray<MetadataBlock>.Empty : builder.ToImmutableAndFree(); } internal static ImmutableArray<AssemblyReaders> MakeAssemblyReaders(this DkmClrInstructionAddress instructionAddress) { var builder = ArrayBuilder<AssemblyReaders>.GetInstance(); foreach (DkmClrModuleInstance module in instructionAddress.RuntimeInstance.GetModulesInAppDomain(instructionAddress.ModuleInstance.AppDomain)) { var symReader = module.GetSymReader(); if (symReader == null) { continue; } MetadataReader reader; unsafe { try { uint size; IntPtr ptr; ptr = module.GetMetaDataBytesPtr(out size); Debug.Assert(size > 0); reader = new MetadataReader((byte*)ptr, (int)size); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } } builder.Add(new AssemblyReaders(reader, symReader)); } return builder.ToImmutableAndFree(); } private static unsafe MetadataBlock GetMetadataBlock(IntPtr ptr, uint size) { var reader = new MetadataReader((byte*)ptr, (int)size); var moduleDef = reader.GetModuleDefinition(); var moduleVersionId = reader.GetGuid(moduleDef.Mvid); var generationId = reader.GetGuid(moduleDef.GenerationId); return new MetadataBlock(moduleVersionId, generationId, ptr, (int)size); } private static MetadataBlock GetMetadataBlock(ImmutableArray<MetadataBlock> previousMetadataBlocks, int index, IntPtr ptr, uint size) { if (!previousMetadataBlocks.IsDefault && index < previousMetadataBlocks.Length) { var previousBlock = previousMetadataBlocks[index]; if (previousBlock.Pointer == ptr && previousBlock.Size == size) { return previousBlock; } } return GetMetadataBlock(ptr, size); } internal static object? GetSymReader(this DkmClrModuleInstance clrModule) { var module = clrModule.Module; // Null if there are no symbols. if (module == null) { return null; } // Use DkmClrModuleInstance.GetSymUnmanagedReader() // rather than DkmModule.GetSymbolInterface() since the // latter does not handle .NET Native modules. return clrModule.GetSymUnmanagedReader(); } internal static DkmCompiledClrInspectionQuery? ToQueryResult( this CompileResult? compResult, DkmCompilerId languageId, ResultProperties resultProperties, DkmClrRuntimeInstance runtimeInstance) { if (compResult == null) { return null; } Debug.Assert(compResult.Assembly != null); Debug.Assert(compResult.TypeName != null); Debug.Assert(compResult.MethodName != null); ReadOnlyCollection<byte>? customTypeInfo; Guid customTypeInfoId = compResult.GetCustomTypeInfo(out customTypeInfo); return DkmCompiledClrInspectionQuery.Create( runtimeInstance, Binary: new ReadOnlyCollection<byte>(compResult.Assembly), DataContainer: null, LanguageId: languageId, TypeName: compResult.TypeName, MethodName: compResult.MethodName, FormatSpecifiers: compResult.FormatSpecifiers, CompilationFlags: resultProperties.Flags, ResultCategory: resultProperties.Category, Access: resultProperties.AccessType, StorageType: resultProperties.StorageType, TypeModifierFlags: resultProperties.ModifierFlags, CustomTypeInfo: customTypeInfo.ToCustomTypeInfo(customTypeInfoId)); } internal static DkmClrCustomTypeInfo? ToCustomTypeInfo(this ReadOnlyCollection<byte>? payload, Guid payloadTypeId) { return (payload == null) ? null : DkmClrCustomTypeInfo.Create(payloadTypeId, payload); } internal static ResultProperties GetResultProperties<TSymbol>(this TSymbol? symbol, DkmClrCompilationResultFlags flags, bool isConstant) where TSymbol : class, ISymbolInternal { var category = (symbol != null) ? GetResultCategory(symbol.Kind) : DkmEvaluationResultCategory.Data; var accessType = (symbol != null) ? GetResultAccessType(symbol.DeclaredAccessibility) : DkmEvaluationResultAccessType.None; var storageType = (symbol != null) && symbol.IsStatic ? DkmEvaluationResultStorageType.Static : DkmEvaluationResultStorageType.None; var modifierFlags = DkmEvaluationResultTypeModifierFlags.None; if (isConstant) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Constant; } else if (symbol is null) { // No change. } else if (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Virtual; } else if (symbol.Kind == SymbolKind.Field && ((IFieldSymbolInternal)symbol).IsVolatile) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Volatile; } // CONSIDER: for completeness, we could check for [MethodImpl(MethodImplOptions.Synchronized)] // and set DkmEvaluationResultTypeModifierFlags.Synchronized, but it doesn't seem to have any // impact on the UI. It is exposed through the DTE, but cscompee didn't set the flag either. return new ResultProperties(flags, category, accessType, storageType, modifierFlags); } private static DkmEvaluationResultCategory GetResultCategory(SymbolKind kind) { switch (kind) { case SymbolKind.Method: return DkmEvaluationResultCategory.Method; case SymbolKind.Property: return DkmEvaluationResultCategory.Property; default: return DkmEvaluationResultCategory.Data; } } private static DkmEvaluationResultAccessType GetResultAccessType(Accessibility accessibility) { switch (accessibility) { case Accessibility.Public: return DkmEvaluationResultAccessType.Public; case Accessibility.Protected: return DkmEvaluationResultAccessType.Protected; case Accessibility.Private: return DkmEvaluationResultAccessType.Private; case Accessibility.Internal: case Accessibility.ProtectedOrInternal: // Dev12 treats this as "internal" case Accessibility.ProtectedAndInternal: // Dev12 treats this as "internal" return DkmEvaluationResultAccessType.Internal; case Accessibility.NotApplicable: return DkmEvaluationResultAccessType.None; default: throw ExceptionUtilities.UnexpectedValue(accessibility); } } internal static bool Includes(this DkmVariableInfoFlags flags, DkmVariableInfoFlags desired) { return (flags & desired) == desired; } internal static MetadataContext<TAssemblyContext> GetMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain) where TAssemblyContext : struct { var dataItem = appDomain.GetDataItem<MetadataContextItem<MetadataContext<TAssemblyContext>>>(); return (dataItem == null) ? default : dataItem.MetadataContext; } internal static void SetMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain, MetadataContext<TAssemblyContext> context, bool report) where TAssemblyContext : struct { if (report) { var process = appDomain.Process; var message = DkmUserMessage.Create( process.Connection, process, DkmUserMessageOutputKind.UnfilteredOutputWindowMessage, $"EE: AppDomain {appDomain.Id}, blocks {context.MetadataBlocks.Length}, contexts {context.AssemblyContexts.Count}" + Environment.NewLine, MessageBoxFlags.MB_OK, 0); message.Post(); } appDomain.SetDataItem(DkmDataCreationDisposition.CreateAlways, new MetadataContextItem<MetadataContext<TAssemblyContext>>(context)); } internal static void RemoveMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain) where TAssemblyContext : struct { appDomain.RemoveDataItem<MetadataContextItem<TAssemblyContext>>(); } private sealed class MetadataContextItem<TMetadataContext> : DkmDataItem where TMetadataContext : struct { internal readonly TMetadataContext MetadataContext; internal MetadataContextItem(TMetadataContext metadataContext) { this.MetadataContext = metadataContext; } } private sealed class AppDomainLifetimeDataItem : DkmDataItem { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Clr.NativeCompilation; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class DkmUtilities { internal unsafe delegate IntPtr GetMetadataBytesPtrFunction(AssemblyIdentity assemblyIdentity, out uint uSize); // Return the set of managed module instances from the AppDomain. private static IEnumerable<DkmClrModuleInstance> GetModulesInAppDomain(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain) { if (appDomain.IsUnloaded) { return SpecializedCollections.EmptyEnumerable<DkmClrModuleInstance>(); } var appDomainId = appDomain.Id; // GetModuleInstances() may include instances of DkmClrNcContainerModuleInstance // which are containers of managed module instances (see GetEmbeddedModules()) // but not managed modules themselves. Since GetModuleInstances() will include the // embedded modules, we can simply ignore DkmClrNcContainerModuleInstances. return runtime.GetModuleInstances(). OfType<DkmClrModuleInstance>(). Where(module => { var moduleAppDomain = module.AppDomain; return !moduleAppDomain.IsUnloaded && (moduleAppDomain.Id == appDomainId); }); } internal static ImmutableArray<MetadataBlock> GetMetadataBlocks( this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain, ImmutableArray<MetadataBlock> previousMetadataBlocks) { // Add a dummy data item to the appdomain to add it to the disposal queue when the debugged process is shutting down. // This should prevent from attempts to use the Metadata pointer for dead debugged processes. if (appDomain.GetDataItem<AppDomainLifetimeDataItem>() == null) { appDomain.SetDataItem(DkmDataCreationDisposition.CreateNew, new AppDomainLifetimeDataItem()); } var builder = ArrayBuilder<MetadataBlock>.GetInstance(); IntPtr ptr; uint size; int index = 0; foreach (DkmClrModuleInstance module in runtime.GetModulesInAppDomain(appDomain)) { MetadataBlock block; try { ptr = module.GetMetaDataBytesPtr(out size); Debug.Assert(size > 0); block = GetMetadataBlock(previousMetadataBlocks, index, ptr, size); } catch (NotImplementedException e) when (module is DkmClrNcModuleInstance) { // DkmClrNcModuleInstance.GetMetaDataBytesPtr not implemented in Dev14. throw new NotImplementedMetadataException(e); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } Debug.Assert(block.ModuleVersionId == module.Mvid); builder.Add(block); index++; } // Include "intrinsic method" assembly. ptr = runtime.GetIntrinsicAssemblyMetaDataBytesPtr(out size); builder.Add(GetMetadataBlock(previousMetadataBlocks, index, ptr, size)); return builder.ToImmutableAndFree(); } internal static ImmutableArray<MetadataBlock> GetMetadataBlocks(GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities) { ArrayBuilder<MetadataBlock>? builder = null; foreach (var missingAssemblyIdentity in missingAssemblyIdentities) { MetadataBlock block; try { uint size; IntPtr ptr; ptr = getMetaDataBytesPtrFunction(missingAssemblyIdentity, out size); Debug.Assert(size > 0); block = GetMetadataBlock(ptr, size); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } if (builder == null) { builder = ArrayBuilder<MetadataBlock>.GetInstance(); } builder.Add(block); } return builder == null ? ImmutableArray<MetadataBlock>.Empty : builder.ToImmutableAndFree(); } internal static ImmutableArray<AssemblyReaders> MakeAssemblyReaders(this DkmClrInstructionAddress instructionAddress) { var builder = ArrayBuilder<AssemblyReaders>.GetInstance(); foreach (DkmClrModuleInstance module in instructionAddress.RuntimeInstance.GetModulesInAppDomain(instructionAddress.ModuleInstance.AppDomain)) { var symReader = module.GetSymReader(); if (symReader == null) { continue; } MetadataReader reader; unsafe { try { uint size; IntPtr ptr; ptr = module.GetMetaDataBytesPtr(out size); Debug.Assert(size > 0); reader = new MetadataReader((byte*)ptr, (int)size); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } } builder.Add(new AssemblyReaders(reader, symReader)); } return builder.ToImmutableAndFree(); } private static unsafe MetadataBlock GetMetadataBlock(IntPtr ptr, uint size) { var reader = new MetadataReader((byte*)ptr, (int)size); var moduleDef = reader.GetModuleDefinition(); var moduleVersionId = reader.GetGuid(moduleDef.Mvid); var generationId = reader.GetGuid(moduleDef.GenerationId); return new MetadataBlock(moduleVersionId, generationId, ptr, (int)size); } private static MetadataBlock GetMetadataBlock(ImmutableArray<MetadataBlock> previousMetadataBlocks, int index, IntPtr ptr, uint size) { if (!previousMetadataBlocks.IsDefault && index < previousMetadataBlocks.Length) { var previousBlock = previousMetadataBlocks[index]; if (previousBlock.Pointer == ptr && previousBlock.Size == size) { return previousBlock; } } return GetMetadataBlock(ptr, size); } internal static object? GetSymReader(this DkmClrModuleInstance clrModule) { var module = clrModule.Module; // Null if there are no symbols. if (module == null) { return null; } // Use DkmClrModuleInstance.GetSymUnmanagedReader() // rather than DkmModule.GetSymbolInterface() since the // latter does not handle .NET Native modules. return clrModule.GetSymUnmanagedReader(); } internal static DkmCompiledClrInspectionQuery? ToQueryResult( this CompileResult? compResult, DkmCompilerId languageId, ResultProperties resultProperties, DkmClrRuntimeInstance runtimeInstance) { if (compResult == null) { return null; } Debug.Assert(compResult.Assembly != null); Debug.Assert(compResult.TypeName != null); Debug.Assert(compResult.MethodName != null); ReadOnlyCollection<byte>? customTypeInfo; Guid customTypeInfoId = compResult.GetCustomTypeInfo(out customTypeInfo); return DkmCompiledClrInspectionQuery.Create( runtimeInstance, Binary: new ReadOnlyCollection<byte>(compResult.Assembly), DataContainer: null, LanguageId: languageId, TypeName: compResult.TypeName, MethodName: compResult.MethodName, FormatSpecifiers: compResult.FormatSpecifiers, CompilationFlags: resultProperties.Flags, ResultCategory: resultProperties.Category, Access: resultProperties.AccessType, StorageType: resultProperties.StorageType, TypeModifierFlags: resultProperties.ModifierFlags, CustomTypeInfo: customTypeInfo.ToCustomTypeInfo(customTypeInfoId)); } internal static DkmClrCustomTypeInfo? ToCustomTypeInfo(this ReadOnlyCollection<byte>? payload, Guid payloadTypeId) { return (payload == null) ? null : DkmClrCustomTypeInfo.Create(payloadTypeId, payload); } internal static ResultProperties GetResultProperties<TSymbol>(this TSymbol? symbol, DkmClrCompilationResultFlags flags, bool isConstant) where TSymbol : class, ISymbolInternal { var category = (symbol != null) ? GetResultCategory(symbol.Kind) : DkmEvaluationResultCategory.Data; var accessType = (symbol != null) ? GetResultAccessType(symbol.DeclaredAccessibility) : DkmEvaluationResultAccessType.None; var storageType = (symbol != null) && symbol.IsStatic ? DkmEvaluationResultStorageType.Static : DkmEvaluationResultStorageType.None; var modifierFlags = DkmEvaluationResultTypeModifierFlags.None; if (isConstant) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Constant; } else if (symbol is null) { // No change. } else if (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Virtual; } else if (symbol.Kind == SymbolKind.Field && ((IFieldSymbolInternal)symbol).IsVolatile) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Volatile; } // CONSIDER: for completeness, we could check for [MethodImpl(MethodImplOptions.Synchronized)] // and set DkmEvaluationResultTypeModifierFlags.Synchronized, but it doesn't seem to have any // impact on the UI. It is exposed through the DTE, but cscompee didn't set the flag either. return new ResultProperties(flags, category, accessType, storageType, modifierFlags); } private static DkmEvaluationResultCategory GetResultCategory(SymbolKind kind) { switch (kind) { case SymbolKind.Method: return DkmEvaluationResultCategory.Method; case SymbolKind.Property: return DkmEvaluationResultCategory.Property; default: return DkmEvaluationResultCategory.Data; } } private static DkmEvaluationResultAccessType GetResultAccessType(Accessibility accessibility) { switch (accessibility) { case Accessibility.Public: return DkmEvaluationResultAccessType.Public; case Accessibility.Protected: return DkmEvaluationResultAccessType.Protected; case Accessibility.Private: return DkmEvaluationResultAccessType.Private; case Accessibility.Internal: case Accessibility.ProtectedOrInternal: // Dev12 treats this as "internal" case Accessibility.ProtectedAndInternal: // Dev12 treats this as "internal" return DkmEvaluationResultAccessType.Internal; case Accessibility.NotApplicable: return DkmEvaluationResultAccessType.None; default: throw ExceptionUtilities.UnexpectedValue(accessibility); } } internal static bool Includes(this DkmVariableInfoFlags flags, DkmVariableInfoFlags desired) { return (flags & desired) == desired; } internal static MetadataContext<TAssemblyContext> GetMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain) where TAssemblyContext : struct { var dataItem = appDomain.GetDataItem<MetadataContextItem<MetadataContext<TAssemblyContext>>>(); return (dataItem == null) ? default : dataItem.MetadataContext; } internal static void SetMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain, MetadataContext<TAssemblyContext> context, bool report) where TAssemblyContext : struct { if (report) { var process = appDomain.Process; var message = DkmUserMessage.Create( process.Connection, process, DkmUserMessageOutputKind.UnfilteredOutputWindowMessage, $"EE: AppDomain {appDomain.Id}, blocks {context.MetadataBlocks.Length}, contexts {context.AssemblyContexts.Count}" + Environment.NewLine, MessageBoxFlags.MB_OK, 0); message.Post(); } appDomain.SetDataItem(DkmDataCreationDisposition.CreateAlways, new MetadataContextItem<MetadataContext<TAssemblyContext>>(context)); } internal static void RemoveMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain) where TAssemblyContext : struct { appDomain.RemoveDataItem<MetadataContextItem<TAssemblyContext>>(); } private sealed class MetadataContextItem<TMetadataContext> : DkmDataItem where TMetadataContext : struct { internal readonly TMetadataContext MetadataContext; internal MetadataContextItem(TMetadataContext metadataContext) { this.MetadataContext = metadataContext; } } private sealed class AppDomainLifetimeDataItem : DkmDataItem { } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/Server/VBCSCompilerTests/RunKeepAliveTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal class RunKeepAliveTests : ExecutionCondition { public override bool ShouldSkip => Environment.GetEnvironmentVariable("RunKeepAliveTests") == null; public override string SkipReason { get; } = "RunKeepAliveTests environment variable not set"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal class RunKeepAliveTests : ExecutionCondition { public override bool ShouldSkip => Environment.GetEnvironmentVariable("RunKeepAliveTests") == null; public override string SkipReason { get; } = "RunKeepAliveTests environment variable not set"; } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.MoveTypeToNamespaceCodeAction.cs
// Licensed to the .NET Foundation under one or more 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.MoveToNamespace { internal abstract partial class AbstractMoveToNamespaceCodeAction { private class MoveTypeToNamespaceCodeAction : AbstractMoveToNamespaceCodeAction { public override string Title => FeaturesResources.Move_to_namespace; public MoveTypeToNamespaceCodeAction(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult) : base(changeNamespaceService, analysisResult) { } } } }
// Licensed to the .NET Foundation under one or more 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.MoveToNamespace { internal abstract partial class AbstractMoveToNamespaceCodeAction { private class MoveTypeToNamespaceCodeAction : AbstractMoveToNamespaceCodeAction { public override string Title => FeaturesResources.Move_to_namespace; public MoveTypeToNamespaceCodeAction(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult) : base(changeNamespaceService, analysisResult) { } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueryManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.GraphModel; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { using Workspace = Microsoft.CodeAnalysis.Workspace; internal class GraphQueryManager { private readonly Workspace _workspace; private readonly IAsynchronousOperationListener _asyncListener; /// <summary> /// This gate locks manipulation of <see cref="_trackedQueries"/>. /// </summary> private readonly object _gate = new(); private readonly List<ValueTuple<WeakReference<IGraphContext>, List<IGraphQuery>>> _trackedQueries = new(); // We update all of our tracked queries when this delay elapses. private ResettableDelay? _delay; internal GraphQueryManager(Workspace workspace, IAsynchronousOperationListener asyncListener) { _workspace = workspace; _asyncListener = asyncListener; } internal void AddQueries(IGraphContext context, List<IGraphQuery> graphQueries) { var asyncToken = _asyncListener.BeginAsyncOperation("GraphQueryManager.AddQueries"); var solution = _workspace.CurrentSolution; var populateTask = PopulateContextGraphAsync(solution, graphQueries, context); // We want to ensure that no matter what happens, this initial context is completed var task = populateTask.SafeContinueWith( _ => context.OnCompleted(), context.CancelToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); if (context.TrackChanges) { task = task.SafeContinueWith( _ => TrackChangesAfterFirstPopulate(graphQueries, context, solution), context.CancelToken, TaskContinuationOptions.None, TaskScheduler.Default); } task.CompletesAsyncOperation(asyncToken); } private void TrackChangesAfterFirstPopulate(List<IGraphQuery> graphQueries, IGraphContext context, Solution solution) { var workspace = solution.Workspace; var contextWeakReference = new WeakReference<IGraphContext>(context); lock (_gate) { if (_trackedQueries.IsEmpty()) { _workspace.WorkspaceChanged += OnWorkspaceChanged; } _trackedQueries.Add(ValueTuple.Create(contextWeakReference, graphQueries)); } EnqueueUpdateIfSolutionIsStale(solution); } private void EnqueueUpdateIfSolutionIsStale(Solution solution) { // It's possible the workspace changed during our initial population, so let's enqueue an update if it did if (_workspace.CurrentSolution != solution) { EnqueueUpdate(); } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) => EnqueueUpdate(); private void EnqueueUpdate() { const int WorkspaceUpdateDelay = 1500; var delay = _delay; if (delay == null) { var newDelay = new ResettableDelay(WorkspaceUpdateDelay, _asyncListener); if (Interlocked.CompareExchange(ref _delay, newDelay, null) == null) { var asyncToken = _asyncListener.BeginAsyncOperation("WorkspaceGraphQueryManager.EnqueueUpdate"); newDelay.Task.SafeContinueWithFromAsync(_ => UpdateAsync(), CancellationToken.None, TaskScheduler.Default) .CompletesAsyncOperation(asyncToken); } return; } delay.Reset(); } private Task UpdateAsync() { List<ValueTuple<IGraphContext, List<IGraphQuery>>> liveQueries; lock (_gate) { liveQueries = _trackedQueries.Select(t => ValueTuple.Create(t.Item1.GetTarget(), t.Item2)).Where(t => t.Item1 != null).ToList()!; } var solution = _workspace.CurrentSolution; var tasks = liveQueries.Select(t => PopulateContextGraphAsync(solution, t.Item2, t.Item1)).ToArray(); var whenAllTask = Task.WhenAll(tasks); return whenAllTask.SafeContinueWith(t => PostUpdate(solution), TaskScheduler.Default); } private void PostUpdate(Solution solution) { _delay = null; lock (_gate) { // See if each context is still alive. It's possible it's already been GC'ed meaning we should stop caring about the query _trackedQueries.RemoveAll(t => !IsTrackingContext(t.Item1)); if (_trackedQueries.IsEmpty()) { _workspace.WorkspaceChanged -= OnWorkspaceChanged; return; } } EnqueueUpdateIfSolutionIsStale(solution); } private static bool IsTrackingContext(WeakReference<IGraphContext> weakContext) { var context = weakContext.GetTarget(); return context != null && !context.CancelToken.IsCancellationRequested; } /// <summary> /// Populate the graph of the context with the values for the given Solution. /// </summary> private static async Task PopulateContextGraphAsync(Solution solution, List<IGraphQuery> graphQueries, IGraphContext context) { try { var cancellationToken = context.CancelToken; var graphBuilderTasks = graphQueries.Select(q => q.GetGraphAsync(solution, context, cancellationToken)).ToArray(); var graphBuilders = await Task.WhenAll(graphBuilderTasks).ConfigureAwait(false); // Perform the actual graph transaction using var transaction = new GraphTransactionScope(); // Remove any links that may have been added by a previous population. We don't // remove nodes to maintain node identity, matching the behavior of the old // providers. context.Graph.Links.Clear(); foreach (var graphBuilder in graphBuilders) { graphBuilder.ApplyToGraph(context.Graph, cancellationToken); context.OutputNodes.AddAll(graphBuilder.GetCreatedNodes(cancellationToken)); } transaction.Complete(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex)) { throw ExceptionUtilities.Unreachable; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.GraphModel; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { using Workspace = Microsoft.CodeAnalysis.Workspace; internal class GraphQueryManager { private readonly Workspace _workspace; private readonly IAsynchronousOperationListener _asyncListener; /// <summary> /// This gate locks manipulation of <see cref="_trackedQueries"/>. /// </summary> private readonly object _gate = new(); private readonly List<ValueTuple<WeakReference<IGraphContext>, List<IGraphQuery>>> _trackedQueries = new(); // We update all of our tracked queries when this delay elapses. private ResettableDelay? _delay; internal GraphQueryManager(Workspace workspace, IAsynchronousOperationListener asyncListener) { _workspace = workspace; _asyncListener = asyncListener; } internal void AddQueries(IGraphContext context, List<IGraphQuery> graphQueries) { var asyncToken = _asyncListener.BeginAsyncOperation("GraphQueryManager.AddQueries"); var solution = _workspace.CurrentSolution; var populateTask = PopulateContextGraphAsync(solution, graphQueries, context); // We want to ensure that no matter what happens, this initial context is completed var task = populateTask.SafeContinueWith( _ => context.OnCompleted(), context.CancelToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); if (context.TrackChanges) { task = task.SafeContinueWith( _ => TrackChangesAfterFirstPopulate(graphQueries, context, solution), context.CancelToken, TaskContinuationOptions.None, TaskScheduler.Default); } task.CompletesAsyncOperation(asyncToken); } private void TrackChangesAfterFirstPopulate(List<IGraphQuery> graphQueries, IGraphContext context, Solution solution) { var workspace = solution.Workspace; var contextWeakReference = new WeakReference<IGraphContext>(context); lock (_gate) { if (_trackedQueries.IsEmpty()) { _workspace.WorkspaceChanged += OnWorkspaceChanged; } _trackedQueries.Add(ValueTuple.Create(contextWeakReference, graphQueries)); } EnqueueUpdateIfSolutionIsStale(solution); } private void EnqueueUpdateIfSolutionIsStale(Solution solution) { // It's possible the workspace changed during our initial population, so let's enqueue an update if it did if (_workspace.CurrentSolution != solution) { EnqueueUpdate(); } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) => EnqueueUpdate(); private void EnqueueUpdate() { const int WorkspaceUpdateDelay = 1500; var delay = _delay; if (delay == null) { var newDelay = new ResettableDelay(WorkspaceUpdateDelay, _asyncListener); if (Interlocked.CompareExchange(ref _delay, newDelay, null) == null) { var asyncToken = _asyncListener.BeginAsyncOperation("WorkspaceGraphQueryManager.EnqueueUpdate"); newDelay.Task.SafeContinueWithFromAsync(_ => UpdateAsync(), CancellationToken.None, TaskScheduler.Default) .CompletesAsyncOperation(asyncToken); } return; } delay.Reset(); } private Task UpdateAsync() { List<ValueTuple<IGraphContext, List<IGraphQuery>>> liveQueries; lock (_gate) { liveQueries = _trackedQueries.Select(t => ValueTuple.Create(t.Item1.GetTarget(), t.Item2)).Where(t => t.Item1 != null).ToList()!; } var solution = _workspace.CurrentSolution; var tasks = liveQueries.Select(t => PopulateContextGraphAsync(solution, t.Item2, t.Item1)).ToArray(); var whenAllTask = Task.WhenAll(tasks); return whenAllTask.SafeContinueWith(t => PostUpdate(solution), TaskScheduler.Default); } private void PostUpdate(Solution solution) { _delay = null; lock (_gate) { // See if each context is still alive. It's possible it's already been GC'ed meaning we should stop caring about the query _trackedQueries.RemoveAll(t => !IsTrackingContext(t.Item1)); if (_trackedQueries.IsEmpty()) { _workspace.WorkspaceChanged -= OnWorkspaceChanged; return; } } EnqueueUpdateIfSolutionIsStale(solution); } private static bool IsTrackingContext(WeakReference<IGraphContext> weakContext) { var context = weakContext.GetTarget(); return context != null && !context.CancelToken.IsCancellationRequested; } /// <summary> /// Populate the graph of the context with the values for the given Solution. /// </summary> private static async Task PopulateContextGraphAsync(Solution solution, List<IGraphQuery> graphQueries, IGraphContext context) { try { var cancellationToken = context.CancelToken; var graphBuilderTasks = graphQueries.Select(q => q.GetGraphAsync(solution, context, cancellationToken)).ToArray(); var graphBuilders = await Task.WhenAll(graphBuilderTasks).ConfigureAwait(false); // Perform the actual graph transaction using var transaction = new GraphTransactionScope(); // Remove any links that may have been added by a previous population. We don't // remove nodes to maintain node identity, matching the behavior of the old // providers. context.Graph.Links.Clear(); foreach (var graphBuilder in graphBuilders) { graphBuilder.ApplyToGraph(context.Graph, cancellationToken); context.OutputNodes.AddAll(graphBuilder.GetCreatedNodes(cancellationToken)); } transaction.Complete(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex)) { throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/AsyncKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class AsyncKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AsyncKeywordRecommender() : base(SyntaxKind.AsyncKeyword, isValidInPreprocessorContext: false) { } private static readonly ISet<SyntaxKind> s_validLocalFunctionModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword }; protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.TargetToken.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword)) { return false; } return InMemberDeclarationContext(position, context, cancellationToken) || context.SyntaxTree.IsLambdaDeclarationContext(position, otherModifier: SyntaxKind.StaticKeyword, cancellationToken) || context.SyntaxTree.IsLocalFunctionDeclarationContext(position, s_validLocalFunctionModifiers, cancellationToken); } private static bool InMemberDeclarationContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || context.SyntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: true, cancellationToken: cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class AsyncKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AsyncKeywordRecommender() : base(SyntaxKind.AsyncKeyword, isValidInPreprocessorContext: false) { } private static readonly ISet<SyntaxKind> s_validLocalFunctionModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword }; protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.TargetToken.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword)) { return false; } return InMemberDeclarationContext(position, context, cancellationToken) || context.SyntaxTree.IsLambdaDeclarationContext(position, otherModifier: SyntaxKind.StaticKeyword, cancellationToken) || context.SyntaxTree.IsLocalFunctionDeclarationContext(position, s_validLocalFunctionModifiers, cancellationToken); } private static bool InMemberDeclarationContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || context.SyntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: true, cancellationToken: cancellationToken); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.ParsedSyntaxTree.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public partial class CSharpSyntaxTree { private class ParsedSyntaxTree : CSharpSyntaxTree { private readonly CSharpParseOptions _options; private readonly string _path; private readonly CSharpSyntaxNode _root; private readonly bool _hasCompilationUnitRoot; private readonly Encoding? _encodingOpt; private readonly SourceHashAlgorithm _checksumAlgorithm; private readonly ImmutableDictionary<string, ReportDiagnostic> _diagnosticOptions; private SourceText? _lazyText; internal ParsedSyntaxTree( SourceText? textOpt, Encoding? encodingOpt, SourceHashAlgorithm checksumAlgorithm, string path, CSharpParseOptions options, CSharpSyntaxNode root, Syntax.InternalSyntax.DirectiveStack directives, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool cloneRoot) { Debug.Assert(root != null); Debug.Assert(options != null); Debug.Assert(textOpt == null || textOpt.Encoding == encodingOpt && textOpt.ChecksumAlgorithm == checksumAlgorithm); _lazyText = textOpt; _encodingOpt = encodingOpt ?? textOpt?.Encoding; _checksumAlgorithm = checksumAlgorithm; _options = options; _path = path ?? string.Empty; _root = cloneRoot ? this.CloneNodeAsRoot(root) : root; _hasCompilationUnitRoot = root.Kind() == SyntaxKind.CompilationUnit; _diagnosticOptions = diagnosticOptions ?? EmptyDiagnosticOptions; this.SetDirectiveStack(directives); } public override string FilePath { get { return _path; } } public override SourceText GetText(CancellationToken cancellationToken) { if (_lazyText == null) { Interlocked.CompareExchange(ref _lazyText, this.GetRoot(cancellationToken).GetText(_encodingOpt, _checksumAlgorithm), null); } return _lazyText; } public override bool TryGetText([NotNullWhen(true)] out SourceText? text) { text = _lazyText; return text != null; } public override Encoding? Encoding { get { return _encodingOpt; } } public override int Length { get { return _root.FullSpan.Length; } } public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken) { return _root; } public override bool TryGetRoot(out CSharpSyntaxNode root) { root = _root; return true; } public override bool HasCompilationUnitRoot { get { return _hasCompilationUnitRoot; } } public override CSharpParseOptions Options { get { return _options; } } [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public override ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => _diagnosticOptions; public override SyntaxReference GetReference(SyntaxNode node) { return new SimpleSyntaxReference(node); } public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) { if (ReferenceEquals(_root, root) && ReferenceEquals(_options, options)) { return this; } return new ParsedSyntaxTree( textOpt: null, _encodingOpt, _checksumAlgorithm, _path, (CSharpParseOptions)options, (CSharpSyntaxNode)root, _directives, _diagnosticOptions, cloneRoot: true); } public override SyntaxTree WithFilePath(string path) { if (_path == path) { return this; } return new ParsedSyntaxTree( _lazyText, _encodingOpt, _checksumAlgorithm, path, _options, _root, _directives, _diagnosticOptions, cloneRoot: true); } [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public override SyntaxTree WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic> options) { if (options is null) { options = EmptyDiagnosticOptions; } if (ReferenceEquals(_diagnosticOptions, options)) { return this; } return new ParsedSyntaxTree( _lazyText, _encodingOpt, _checksumAlgorithm, _path, _options, _root, _directives, options, cloneRoot: 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.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public partial class CSharpSyntaxTree { private class ParsedSyntaxTree : CSharpSyntaxTree { private readonly CSharpParseOptions _options; private readonly string _path; private readonly CSharpSyntaxNode _root; private readonly bool _hasCompilationUnitRoot; private readonly Encoding? _encodingOpt; private readonly SourceHashAlgorithm _checksumAlgorithm; private readonly ImmutableDictionary<string, ReportDiagnostic> _diagnosticOptions; private SourceText? _lazyText; internal ParsedSyntaxTree( SourceText? textOpt, Encoding? encodingOpt, SourceHashAlgorithm checksumAlgorithm, string path, CSharpParseOptions options, CSharpSyntaxNode root, Syntax.InternalSyntax.DirectiveStack directives, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool cloneRoot) { Debug.Assert(root != null); Debug.Assert(options != null); Debug.Assert(textOpt == null || textOpt.Encoding == encodingOpt && textOpt.ChecksumAlgorithm == checksumAlgorithm); _lazyText = textOpt; _encodingOpt = encodingOpt ?? textOpt?.Encoding; _checksumAlgorithm = checksumAlgorithm; _options = options; _path = path ?? string.Empty; _root = cloneRoot ? this.CloneNodeAsRoot(root) : root; _hasCompilationUnitRoot = root.Kind() == SyntaxKind.CompilationUnit; _diagnosticOptions = diagnosticOptions ?? EmptyDiagnosticOptions; this.SetDirectiveStack(directives); } public override string FilePath { get { return _path; } } public override SourceText GetText(CancellationToken cancellationToken) { if (_lazyText == null) { Interlocked.CompareExchange(ref _lazyText, this.GetRoot(cancellationToken).GetText(_encodingOpt, _checksumAlgorithm), null); } return _lazyText; } public override bool TryGetText([NotNullWhen(true)] out SourceText? text) { text = _lazyText; return text != null; } public override Encoding? Encoding { get { return _encodingOpt; } } public override int Length { get { return _root.FullSpan.Length; } } public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken) { return _root; } public override bool TryGetRoot(out CSharpSyntaxNode root) { root = _root; return true; } public override bool HasCompilationUnitRoot { get { return _hasCompilationUnitRoot; } } public override CSharpParseOptions Options { get { return _options; } } [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public override ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => _diagnosticOptions; public override SyntaxReference GetReference(SyntaxNode node) { return new SimpleSyntaxReference(node); } public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) { if (ReferenceEquals(_root, root) && ReferenceEquals(_options, options)) { return this; } return new ParsedSyntaxTree( textOpt: null, _encodingOpt, _checksumAlgorithm, _path, (CSharpParseOptions)options, (CSharpSyntaxNode)root, _directives, _diagnosticOptions, cloneRoot: true); } public override SyntaxTree WithFilePath(string path) { if (_path == path) { return this; } return new ParsedSyntaxTree( _lazyText, _encodingOpt, _checksumAlgorithm, path, _options, _root, _directives, _diagnosticOptions, cloneRoot: true); } [Obsolete("Obsolete due to performance problems, use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public override SyntaxTree WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic> options) { if (options is null) { options = EmptyDiagnosticOptions; } if (ReferenceEquals(_diagnosticOptions, options)) { return this; } return new ParsedSyntaxTree( _lazyText, _encodingOpt, _checksumAlgorithm, _path, _options, _root, _directives, options, cloneRoot: true); } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/ObjectListKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal enum ObjectListKind { None, BaseTypes, Hierarchy, Members, Namespaces, Projects, References, Types } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal enum ObjectListKind { None, BaseTypes, Hierarchy, Members, Namespaces, Projects, References, Types } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEventAccessorSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Event accessor that has been synthesized for a field-like event declared in source, /// or for an event re-abstraction in an interface. /// </summary> /// <remarks> /// Associated with <see cref="SourceFieldLikeEventSymbol"/> and <see cref="SourceCustomEventSymbol"/>. /// </remarks> internal sealed class SynthesizedEventAccessorSymbol : SourceEventAccessorSymbol { // Since we don't have a syntax reference, we'll have to use another object for locking. private readonly object _methodChecksLockObject = new object(); internal SynthesizedEventAccessorSymbol(SourceEventSymbol @event, bool isAdder, EventSymbol explicitlyImplementedEventOpt = null, string aliasQualifierOpt = null) : base(@event, null, @event.Locations, explicitlyImplementedEventOpt, aliasQualifierOpt, isAdder, isIterator: false, isNullableAnalysisEnabled: false) { } public override bool IsImplicitlyDeclared { get { return true; } } internal override bool GenerateDebugInfo { get { return false; } } protected override SourceMemberMethodSymbol BoundAttributesSource { get { return this.MethodKind == MethodKind.EventAdd ? (SourceMemberMethodSymbol)this.AssociatedEvent.RemoveMethod : null; } } protected override IAttributeTargetSymbol AttributeOwner { get { // attributes for this accessor are specified on the associated event: return AssociatedEvent; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { return OneOrMany.Create(this.AssociatedEvent.AttributeDeclarationSyntaxList); } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } protected override object MethodChecksLockObject { get { return _methodChecksLockObject; } } internal override MethodImplAttributes ImplementationAttributes { get { MethodImplAttributes result = base.ImplementationAttributes; if (!IsAbstract && !AssociatedEvent.IsWindowsRuntimeEvent && !ContainingType.IsStructType() && (object)DeclaringCompilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T) == null) { // Under these conditions, this method needs to be synchronized. result |= MethodImplAttributes.Synchronized; } return result; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Event accessor that has been synthesized for a field-like event declared in source, /// or for an event re-abstraction in an interface. /// </summary> /// <remarks> /// Associated with <see cref="SourceFieldLikeEventSymbol"/> and <see cref="SourceCustomEventSymbol"/>. /// </remarks> internal sealed class SynthesizedEventAccessorSymbol : SourceEventAccessorSymbol { // Since we don't have a syntax reference, we'll have to use another object for locking. private readonly object _methodChecksLockObject = new object(); internal SynthesizedEventAccessorSymbol(SourceEventSymbol @event, bool isAdder, EventSymbol explicitlyImplementedEventOpt = null, string aliasQualifierOpt = null) : base(@event, null, @event.Locations, explicitlyImplementedEventOpt, aliasQualifierOpt, isAdder, isIterator: false, isNullableAnalysisEnabled: false) { } public override bool IsImplicitlyDeclared { get { return true; } } internal override bool GenerateDebugInfo { get { return false; } } protected override SourceMemberMethodSymbol BoundAttributesSource { get { return this.MethodKind == MethodKind.EventAdd ? (SourceMemberMethodSymbol)this.AssociatedEvent.RemoveMethod : null; } } protected override IAttributeTargetSymbol AttributeOwner { get { // attributes for this accessor are specified on the associated event: return AssociatedEvent; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { return OneOrMany.Create(this.AssociatedEvent.AttributeDeclarationSyntaxList); } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } protected override object MethodChecksLockObject { get { return _methodChecksLockObject; } } internal override MethodImplAttributes ImplementationAttributes { get { MethodImplAttributes result = base.ImplementationAttributes; if (!IsAbstract && !AssociatedEvent.IsWindowsRuntimeEvent && !ContainingType.IsStructType() && (object)DeclaringCompilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T) == null) { // Under these conditions, this method needs to be synchronized. result |= MethodImplAttributes.Synchronized; } return result; } } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Compilers/CSharp/Portable/Symbols/Attributes/WellKnownAttributeData/ReturnTypeWellKnownAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class ReturnTypeWellKnownAttributeData : CommonReturnTypeWellKnownAttributeData { private bool _hasMaybeNullAttribute; public bool HasMaybeNullAttribute { get { VerifySealed(expected: true); return _hasMaybeNullAttribute; } set { VerifySealed(expected: false); _hasMaybeNullAttribute = value; SetDataStored(); } } private bool _hasNotNullAttribute; public bool HasNotNullAttribute { get { VerifySealed(expected: true); return _hasNotNullAttribute; } set { VerifySealed(expected: false); _hasNotNullAttribute = value; SetDataStored(); } } private ImmutableHashSet<string> _notNullIfParameterNotNull = ImmutableHashSet<string>.Empty; public ImmutableHashSet<string> NotNullIfParameterNotNull { get { VerifySealed(expected: true); return _notNullIfParameterNotNull; } } public void AddNotNullIfParameterNotNull(string parameterName) { VerifySealed(expected: false); // The common case is zero or one attribute _notNullIfParameterNotNull = _notNullIfParameterNotNull.Add(parameterName); SetDataStored(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class ReturnTypeWellKnownAttributeData : CommonReturnTypeWellKnownAttributeData { private bool _hasMaybeNullAttribute; public bool HasMaybeNullAttribute { get { VerifySealed(expected: true); return _hasMaybeNullAttribute; } set { VerifySealed(expected: false); _hasMaybeNullAttribute = value; SetDataStored(); } } private bool _hasNotNullAttribute; public bool HasNotNullAttribute { get { VerifySealed(expected: true); return _hasNotNullAttribute; } set { VerifySealed(expected: false); _hasNotNullAttribute = value; SetDataStored(); } } private ImmutableHashSet<string> _notNullIfParameterNotNull = ImmutableHashSet<string>.Empty; public ImmutableHashSet<string> NotNullIfParameterNotNull { get { VerifySealed(expected: true); return _notNullIfParameterNotNull; } } public void AddNotNullIfParameterNotNull(string parameterName) { VerifySealed(expected: false); // The common case is zero or one attribute _notNullIfParameterNotNull = _notNullIfParameterNotNull.Add(parameterName); SetDataStored(); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/MSBuild/MSBuild/CSharp/CSharpCommandLineArgumentReader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.MSBuild; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.CSharp { internal class CSharpCommandLineArgumentReader : CommandLineArgumentReader { private CSharpCommandLineArgumentReader(MSB.Execution.ProjectInstance project) : base(project) { } public static ImmutableArray<string> Read(MSB.Execution.ProjectInstance project) { return new CSharpCommandLineArgumentReader(project).Read(); } protected override void ReadCore() { ReadAdditionalFiles(); ReadAnalyzers(); ReadCodePage(); ReadDebugInfo(); ReadDelaySign(); ReadErrorReport(); ReadFeatures(); ReadImports(); ReadPlatform(); ReadReferences(); ReadSigning(); AddIfNotNullOrWhiteSpace("appconfig", Project.ReadPropertyString(PropertyNames.AppConfigForCompiler)); AddIfNotNullOrWhiteSpace("baseaddress", Project.ReadPropertyString(PropertyNames.BaseAddress)); AddIfTrue("checked", Project.ReadPropertyBool(PropertyNames.CheckForOverflowUnderflow)); AddIfNotNullOrWhiteSpace("define", Project.ReadPropertyString(PropertyNames.DefineConstants)); AddIfNotNullOrWhiteSpace("filealign", Project.ReadPropertyString(PropertyNames.FileAlignment)); AddIfNotNullOrWhiteSpace("doc", Project.ReadItemsAsString(ItemNames.DocFileItem)); AddIfTrue("fullpaths", Project.ReadPropertyBool(PropertyNames.GenerateFullPaths)); AddIfTrue("highentropyva", Project.ReadPropertyBool(PropertyNames.HighEntropyVA)); AddIfNotNullOrWhiteSpace("langversion", Project.ReadPropertyString(PropertyNames.LangVersion)); AddIfNotNullOrWhiteSpace("main", Project.ReadPropertyString(PropertyNames.StartupObject)); AddIfNotNullOrWhiteSpace("moduleassemblyname", Project.ReadPropertyString(PropertyNames.ModuleAssemblyName)); AddIfTrue("nostdlib", Project.ReadPropertyBool(PropertyNames.NoCompilerStandardLib)); AddIfNotNullOrWhiteSpace("nowarn", Project.ReadPropertyString(PropertyNames.NoWarn)); AddIfTrue("optimize", Project.ReadPropertyBool(PropertyNames.Optimize)); AddIfNotNullOrWhiteSpace("out", Project.ReadItemsAsString(PropertyNames.IntermediateAssembly)); AddIfNotNullOrWhiteSpace("pdb", Project.ReadPropertyString(PropertyNames.PdbFile)); AddIfNotNullOrWhiteSpace("ruleset", Project.ReadPropertyString(PropertyNames.ResolvedCodeAnalysisRuleSet)); AddIfNotNullOrWhiteSpace("subsystemversion", Project.ReadPropertyString(PropertyNames.SubsystemVersion)); AddIfNotNullOrWhiteSpace("target", Project.ReadPropertyString(PropertyNames.OutputType)); AddIfTrue("unsafe", Project.ReadPropertyBool(PropertyNames.AllowUnsafeBlocks)); Add("warn", Project.ReadPropertyInt(PropertyNames.WarningLevel)); AddIfTrue("warnaserror", Project.ReadPropertyBool(PropertyNames.TreatWarningsAsErrors)); AddIfNotNullOrWhiteSpace("warnaserror+", Project.ReadPropertyString(PropertyNames.WarningsAsErrors)); AddIfNotNullOrWhiteSpace("warnaserror-", Project.ReadPropertyString(PropertyNames.WarningsNotAsErrors)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.MSBuild; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.CSharp { internal class CSharpCommandLineArgumentReader : CommandLineArgumentReader { private CSharpCommandLineArgumentReader(MSB.Execution.ProjectInstance project) : base(project) { } public static ImmutableArray<string> Read(MSB.Execution.ProjectInstance project) { return new CSharpCommandLineArgumentReader(project).Read(); } protected override void ReadCore() { ReadAdditionalFiles(); ReadAnalyzers(); ReadCodePage(); ReadDebugInfo(); ReadDelaySign(); ReadErrorReport(); ReadFeatures(); ReadImports(); ReadPlatform(); ReadReferences(); ReadSigning(); AddIfNotNullOrWhiteSpace("appconfig", Project.ReadPropertyString(PropertyNames.AppConfigForCompiler)); AddIfNotNullOrWhiteSpace("baseaddress", Project.ReadPropertyString(PropertyNames.BaseAddress)); AddIfTrue("checked", Project.ReadPropertyBool(PropertyNames.CheckForOverflowUnderflow)); AddIfNotNullOrWhiteSpace("define", Project.ReadPropertyString(PropertyNames.DefineConstants)); AddIfNotNullOrWhiteSpace("filealign", Project.ReadPropertyString(PropertyNames.FileAlignment)); AddIfNotNullOrWhiteSpace("doc", Project.ReadItemsAsString(ItemNames.DocFileItem)); AddIfTrue("fullpaths", Project.ReadPropertyBool(PropertyNames.GenerateFullPaths)); AddIfTrue("highentropyva", Project.ReadPropertyBool(PropertyNames.HighEntropyVA)); AddIfNotNullOrWhiteSpace("langversion", Project.ReadPropertyString(PropertyNames.LangVersion)); AddIfNotNullOrWhiteSpace("main", Project.ReadPropertyString(PropertyNames.StartupObject)); AddIfNotNullOrWhiteSpace("moduleassemblyname", Project.ReadPropertyString(PropertyNames.ModuleAssemblyName)); AddIfTrue("nostdlib", Project.ReadPropertyBool(PropertyNames.NoCompilerStandardLib)); AddIfNotNullOrWhiteSpace("nowarn", Project.ReadPropertyString(PropertyNames.NoWarn)); AddIfTrue("optimize", Project.ReadPropertyBool(PropertyNames.Optimize)); AddIfNotNullOrWhiteSpace("out", Project.ReadItemsAsString(PropertyNames.IntermediateAssembly)); AddIfNotNullOrWhiteSpace("pdb", Project.ReadPropertyString(PropertyNames.PdbFile)); AddIfNotNullOrWhiteSpace("ruleset", Project.ReadPropertyString(PropertyNames.ResolvedCodeAnalysisRuleSet)); AddIfNotNullOrWhiteSpace("subsystemversion", Project.ReadPropertyString(PropertyNames.SubsystemVersion)); AddIfNotNullOrWhiteSpace("target", Project.ReadPropertyString(PropertyNames.OutputType)); AddIfTrue("unsafe", Project.ReadPropertyBool(PropertyNames.AllowUnsafeBlocks)); Add("warn", Project.ReadPropertyInt(PropertyNames.WarningLevel)); AddIfTrue("warnaserror", Project.ReadPropertyBool(PropertyNames.TreatWarningsAsErrors)); AddIfNotNullOrWhiteSpace("warnaserror+", Project.ReadPropertyString(PropertyNames.WarningsAsErrors)); AddIfNotNullOrWhiteSpace("warnaserror-", Project.ReadPropertyString(PropertyNames.WarningsNotAsErrors)); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/EditorFeatures/CSharpTest2/Recommendations/DefaultKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 DefaultKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor2() { await VerifyAbsenceAsync( @"class C { #if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#line $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# line $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSwitch() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCase() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { case 0: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDefault() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOneStatement() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTwoStatements() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine(); Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIfElse() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: if (goo) { } else { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIncompleteStatement() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine( $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideBlock() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCompleteIf() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: if (goo) Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIncompleteIf() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: if (goo) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhile() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: while (true) { } $$")); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGotoInSwitch() { await VerifyAbsenceAsync(AddInsideMethod( @"switch (expr) { default: goto $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGotoOutsideSwitch() { await VerifyAbsenceAsync(AddInsideMethod( @"goto $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDefault() { await VerifyAbsenceAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(46283, "https://github.com/dotnet/roslyn/issues/46283")] public async Task TestInTypeParameterConstraint() { await VerifyKeywordAsync( @"class C { void M<T>() where T : $$ { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(46283, "https://github.com/dotnet/roslyn/issues/46283")] public async Task TestInTypeParameterConstraint_InOverride() { await VerifyKeywordAsync( @"class C : Base { public override void M<T>() where T : $$ { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(46283, "https://github.com/dotnet/roslyn/issues/46283")] public async Task TestInTypeParameterConstraint_InExplicitInterfaceImplementation() { await VerifyKeywordAsync( @"class C : I { public void I.M<T>() where T : $$ { } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 DefaultKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor2() { await VerifyAbsenceAsync( @"class C { #if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#line $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# line $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSwitch() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCase() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { case 0: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDefault() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOneStatement() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTwoStatements() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine(); Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIfElse() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: if (goo) { } else { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIncompleteStatement() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: Console.WriteLine( $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideBlock() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: { $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCompleteIf() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: if (goo) Console.WriteLine(); $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIncompleteIf() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: if (goo) $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhile() { await VerifyKeywordAsync(AddInsideMethod( @"switch (expr) { default: while (true) { } $$")); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGotoInSwitch() { await VerifyAbsenceAsync(AddInsideMethod( @"switch (expr) { default: goto $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGotoOutsideSwitch() { await VerifyAbsenceAsync(AddInsideMethod( @"goto $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDefault() { await VerifyAbsenceAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(46283, "https://github.com/dotnet/roslyn/issues/46283")] public async Task TestInTypeParameterConstraint() { await VerifyKeywordAsync( @"class C { void M<T>() where T : $$ { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(46283, "https://github.com/dotnet/roslyn/issues/46283")] public async Task TestInTypeParameterConstraint_InOverride() { await VerifyKeywordAsync( @"class C : Base { public override void M<T>() where T : $$ { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(46283, "https://github.com/dotnet/roslyn/issues/46283")] public async Task TestInTypeParameterConstraint_InExplicitInterfaceImplementation() { await VerifyKeywordAsync( @"class C : I { public void I.M<T>() where T : $$ { } }"); } } }
-1
dotnet/roslyn
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./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
55,039
Mark record struct generated methods as readonly where possible
Fixes https://github.com/dotnet/roslyn/issues/54419
AndreyTretyak
2021-07-22T02:57:48Z
2021-08-10T21:52:23Z
96837390a2b61528b60b88b8bf8ccace0515cbaa
ba75cb8c43275d935110cb4138f7bc68a75c2957
Mark record struct generated methods as readonly where possible. Fixes https://github.com/dotnet/roslyn/issues/54419
./src/Workspaces/Core/Portable/Workspace/Host/Caching/CacheOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Options; namespace Microsoft.CodeAnalysis.Host { internal static class CacheOptions { internal static readonly Option2<int> RecoverableTreeLengthThreshold = new(nameof(CacheOptions), "RecoverableTreeLengthThreshold", defaultValue: 4096, storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\Cache\RecoverableTreeLengthThreshold")); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Options; namespace Microsoft.CodeAnalysis.Host { internal static class CacheOptions { internal static readonly Option2<int> RecoverableTreeLengthThreshold = new(nameof(CacheOptions), "RecoverableTreeLengthThreshold", defaultValue: 4096, storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\Cache\RecoverableTreeLengthThreshold")); } }
-1